1

I have some questions related to memory structure.

Are stack and heap determined by OS? or physically are they separated?

If they are determined by OS, which OS has the stack and heap as component of memory structure except Windows?

As I know default stack size is 1MB and I can expand the size manually, but why default size is so small?

And if stack size is 1MB, I can not hold data that exceed 1MB in a local variable?

And my last question is, is there any reason that programmer needs to be more aware of memory structure if he writes unmanaged code (e.g. native C++) rather than managed code (e.g. C#)?

Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137
Jackson
  • 17
  • 5
  • 1
    you might find answers to your question here http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap – Maytham Fahmi Sep 18 '15 at 14:23

1 Answers1

1

The default stack size depends on the operating system. Some are small, some are large. The stack and the heap are "physically separated" in the sense that their addresses are different.

The reasons the differences are significant to programmers are many:

  • allocations on the stack are automatically deallocated when the function/method returns
  • large allocations on the stack may run out of memory even though the machine has free memory (due to stack size limitations)
  • in some environments (eg C#, Java, Python, JavaScript) while all local variables are allocated on the stack (as in C, C++) the variables allocated on the stack are all references (similar to pointers) and so always use a constant small amount of stack memory
  • recursion or deep function/method calling can run out of stack space
  • allocation and deallocation on the stack is faster than on the heap (the compiler computes the size and includes it in a single pointer move operation when the function is entered, no free lists to scan or anything -- this applies to C and C++ but not to C#, Java, etc.)
  • never return a pointer to data allocated on the stack; if you do then sometime later you will at best crash your program and at worst not know what data corruption has occurred
  • allocations on the stack can never cause memory leaks; allocations on the heap can be leaked
  • data on the stack is local to the function (unless it passes a pointer to it to a function it calls) and thus is thread-safe; data on the heap might be accessible from more than one thread and may need proper synchronization controls
dsh
  • 12,037
  • 3
  • 33
  • 51
  • Your third point is untrue for C# in at least two regards - local variables may have been captured by lambdas or continuations and so actually reside on the heap, and value types stored on the stack *are* stored as values, not references. Can't speak for the other languages there. – Damien_The_Unbeliever Sep 18 '15 at 14:48