Saturday, October 3, 2009

Stack vs. Heap: Overview

Both deal with how memory is managed

Stack
Heap
Inside program (Program space)
Outside program (Managed by OS)
Fast
Slow (because of system calls to allocate memory)
Run-time variables (function parameters, return address, return value, primitives)
Dynamically allocated variables (Objects)
Global and static variables
Stack variables are destroyed automatically when out of scope
Heap variables are destroyed when manually de-allocated

Note: If memory is never de-allocated then a memory leak occurs
needs initialization
needs allocation
small memory space

Note: If to much memory is allocated on the stack then we have a stack overflow. This is dangerous because it can corrupt memory or cause exploitative code to be executed.
relatively large memory space

Examples
int i = 123;                   // on stack
int stackArray[256];           // also on stack
int *heapArray = new int[256]; // on heap


Sources
Stack-based memory allocation
Dynamic memory allocation
What is stack & heap?
Heap vs. Stack

No comments:

Post a Comment