Structs on stack classes on heap

91 views Asked by At

Everyone knows that structs are value types and classes are reference types and that therefore structs are allocated on the stack and that objects are allocated on the heap.

What I'd like to know is what is the implication of something being allocated on the stack as opposed to something being allocated on the heap?

1

There are 1 answers

2
mattnedrich On BEST ANSWER

One general implication of allocating memory on the stack is that it is lost once it leaves scope (e.g., function/method returns). Heap memory can persist longer and need not worry about things like that.

Update:
Another important item that I didn't mention is that heap memory must be managed by someone. Depending on the language this can be the programmer (C, C++, etc.), a garbage collector (Java, C#, etc.). If heap memory isn't cleaned up when it's done being used you end up with memory leaks.