Saturday, June 5, 2010

Whats what of Stack, Heap, Data Seg, Code Seg

The stack is;
- The area of memory where return values, function parameters, local variables are stored
- A LIFO structure the last data in is the first data out.
- the stake generally runs backwards in memory growing towards the start of memory
- In multi-threaded applications each thread has it own stack, that is created and destroyed with the thread.

The Heap is;
- The area of memory where more persistent variables are stored, such as malloc'ed or newed objects,
- it is generally located after the static compile time data like consts, globals etc. OR at the start of the programs address space
- In multi-threaded applications the heap is shared.

The data and BSS segment is;
- The area of memory where global, static and constants variables are stored
- its layout is compile time decided
- it generally is in front of the heap or after the stack (its exact location is very compiler/OS dependent)
- BSS is uninitialized data
- Data is initialized.
- In multi-threaded applications the data and BSS is shared.

The code segment is;
- The area of memory when the compiled machine code is stored and executed from
- it is generally behind the stack.
- In multi-threaded applications the code seg is shared.

int[4] globalInited = {1,2,3,4}; //Data seg
int[4] globalUninited ;  //BSS seg
static int[4] staticInited = {1,2,3,4}; //Data seg
const  int[4] constInited = {1,2,3,4}; //Data seg

int main()
{
 int *stackPtr; // On the stack
 stackPtr  = (int *)malloc(4 * sizeof(int)); // The malloc is in the heap
 int stackArr[4]; // On the stack
}

No comments:

Post a Comment