Size of stack and heap memory

Vivek Maran picture Vivek Maran · Oct 2, 2012 · Viewed 63.6k times · Source

Possible Duplicate:
What and where are the stack and heap?

With regard to the basic concepts of memory layout in a c program, I understand the that:

  • The language uses two primary data structures stack and heap.
  • Stack is created to store the local variables and book keeping data of subroutines
  • Heap is created to store the dynamically allocated variables of the program
  • Heap is of variable length in nature.(Not very sure on stack)
  • Normally it is the responsibility of the compiler/Language to request the OS to create these data structures before the execution.

Questions

  • What is the initial size with which a stack/heap is created? and who decides it?
  • Wherein physical memory are they are created? I see a general description as "Stack is created in the top-level-address and the heap at the low-level-address" Please elobarate this

Answer

Steve Jessop picture Steve Jessop · Oct 2, 2012

"Stack is created in the top-level-address and the heap at the low-level-address" Please elobarate this

This is a myth. It may have a basis in historical truth. It might sometimes resonate with things you see in real life. But it is not literally true.

It's easy enough to explore, though:

#include <stdlib.h>
#include <stdio.h>

void check(int depth) {
    char c;
    char *ptr = malloc(1);
    printf("stack at %p, heap at %p\n", &c, ptr);
    if (depth <= 0) return;
    check(depth-1);
}

int main() {
    check(10);
    return 0;
}

On my machine I see:

stack at 0x22ac3b, heap at 0x20010240
stack at 0x22ac0b, heap at 0x200485b0
stack at 0x22abdb, heap at 0x200485c0
stack at 0x22abab, heap at 0x200485d0
stack at 0x22ab7b, heap at 0x200485e0
stack at 0x22ab4b, heap at 0x200485f0
stack at 0x22ab1b, heap at 0x20048600
stack at 0x22aaeb, heap at 0x20048610
stack at 0x22aabb, heap at 0x20048620
stack at 0x22aa8b, heap at 0x20048630
stack at 0x22aa5b, heap at 0x20048640

So, the stack is going downwards and the heap is going upwards (as you might expect based on the myth), but the stack has the smaller address, and they are not growing toward each other (myth busted).

Btw, my check function is tail-recursive, and on some implementations with some compiler options you might see the stack not moving at all. Which tells you something about why the standard doesn't mandate how all this works -- if it did it might inadvertently forbid useful optimizations.