Monday, July 31, 2006

Stack and Heap

When a program is loaded into memory, it is organized into three areas of memory, called segments: the text segment, stack segment, and heap segment. The text segment (sometimes also called the code segment) is where the compiled code of the program itself resides.The stack is where memory is allocated for automatic variables within functions.
A stack is a Last In First Out (LIFO) storage device where new storage is allocated and deallocated at only one ``end''.
The heap segment provides more stable storage of data for a program; memory allocated in the heap remains in existence for the duration of a program. Therefore, global variables (storage class external), and static variables are allocated on the heap. Dynamic memory is allocated on the heap by the system. If you created an object on the heap. Its your responsibility to clean/free it up.

Advantages of stack:

- Size required determined at compile-time, so no need at run time to determine amount of memory to allocate at run time. This is obviously a performance advantage.
- Automatic "clean-up".

Advantages of heap (or why you need to use it)

- As size is determined at compile time, it is inflexible. Therefore heap is used when amount required is variable
- As stack cleans up automatically at exit of function, if you still need the memory on exit of function, use the heap.
char *str;
str = malloc(100); /* allocate 100 byte storage object in heap storage put the pointer to it into str */
free(str); /* kill the allocated storage object */
*str = 'h'; /* str is now a dangling reference! attempt to put the character 'h' to what is pointed at by str, but str points to a dead object */

Check the link

No comments:

Post a Comment