-2

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?

Jonathan Nixon
  • 4,756
  • 4
  • 37
  • 51
Sachin Kainth
  • 41,237
  • 78
  • 185
  • 289
  • 1
    Your first sentence contains a few errors. Anyway, the stack is full quicker. What are your actual concerns? – CodeCaster Dec 05 '13 at 14:48
  • possible duplicate of [What and where are the stack and heap?](http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap) – user247702 Dec 05 '13 at 14:49
  • 3
    Value types aren't always allocated in the stack. Read more about how the C# implementation treats value types: http://blogs.msdn.com/b/ericlippert/archive/2010/09/30/the-truth-about-value-types.aspx – dcastro Dec 05 '13 at 14:52
  • 2
    @dcastro it's been too long since I'd last seen that, I'd forgotten how much fun it is to read! – AakashM Dec 05 '13 at 15:00
  • There are tons and tons of resources out there on this issue. You appear to have spent no time doing research into the issue before asking this question. – Servy Dec 05 '13 at 15:11

1 Answers1

1

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.

mattnedrich
  • 5,471
  • 8
  • 30
  • 40