Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/articles/c-tutorials/)
-   -   Stack Vs Heap (http://www.go4expert.com/articles/stack-vs-heap-t16171/)

shabbir 13Feb2009 16:55

Stack Vs Heap
 

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: Cpp

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.

shabbir 4Mar2009 09:56

Re: Stack Vs Heap
 
Nominate this article for Article of the month for February 2009


All times are GMT +5.5. The time now is 00:33.