1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Stack Vs Heap

Discussion in 'C' started by shabbir, Feb 13, 2009.

  1. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,283
    Likes Received:
    364
    Trophy Points:
    83

    Stack memory



    Let's suppose there is nothing on the stack to begin with. One of the functions either the calling function or the called function depending on the calling convention would start a stack.

    Lets take a very simple C / C++ program to see how things would work.

    Code:
    int func(int i)
    {
    	int p = 10;
    	return p;
    }
    
    int main()
    {
    	int x = func(4);
    }
    
    Now we Assume the Stack is Empty and if this does not go down your throat you can assume the snapshot of the stack is such that we start from a point where the stack pointer points is Zero.

    Code:
    |-----------|
    |           |
    |-----------|
    |           |
    |-----------|
    |           |
    |-----------|
    |     4     | <-- Stack Pointer
    |-----------|
    
    Now The func(4) is started execution.

    So the first thing compiler needs to do ( In terms of Stack Memory Allocation ) is pass the variable 4 to the called function.

    So it would Push 4 into the Stack and advance the stack pointer to the Next Location and call the function func.
    Code:
    |-----------|
    |           |
    |-----------|
    |           |
    |-----------|
    |           | <-- Stack Pointer
    |-----------|
    |     4     | 
    |-----------| 
    
    Now when p is defined inside the function func it would define at the Stak pointer. Thus all variables declared inside func are declared in stack.

    Just before func returns, it decreases the Stack pointer and then jumps back to that original return address making variables out of scope for func. If you access the memory location the values would still be persistent but they would not have any reference and can be over written by variables defined in the called function.

    Heap memory



    Heap consists of memory that can be allocated at run time and its something like a pool of memory from which you can request some chunk of it. It is independent of the function making a request and as your program does not take care of cleaning it up it's the programmer's job to deal with heap memory. The size of objects allocated on the heap is often not known to the compiler - therefore the programmer must allocate and release the memory specifically.
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,283
    Likes Received:
    364
    Trophy Points:
    83

Share This Page