Monday, October 12, 2009

Difference between Stack memory and Heap Memory.

Recently I came across the difference between stack/heap topic. In simple, Both are dynamic memory allocated for program execution, but not the only 2 memory regions allocated for program execution.

Please Google “stack, heap” for the definition, summary for the difference:

Heap
- free-list - list of free space
- on allocation - memory manager finds space and marks it as used changing free-list
- on de-allocation - memory manager marks space as free changing free-list
- memory fragmentation - memory fragments into small blocks over lifetime of program
- garbage collection - coalesce fragments, possibly moving objects (must be careful of pointers when moving!)
- Concept at Operating system Memory management layer.

Stack
- clean and efficient support for nested functions and recursion
- central concept is stack frame (also called activation record)
- Concept at Micro Processor hardware registers layer.

Simple Example:

void foo()
{
    int x;                     <<< x is on the stack
    char *ptr = new char[255];
<<< 255 characters are allocated in the heap, but ptr object is on the stack
    int array[255];            <<< 255 ints are all on the stack
}

1 comment: