Difference between Stack & Heap

-- Sponsered Links --

‘Stack’ is a common name for the memory space in which automatic variables (and often function parameters) are allocated.




‘Heap’ is a common name for the “free store”, the memory space where dynamic objects are allocated (see “new” and “delete”).

The stack is used to allocate temporary objects while the heap is used by a programmer to reserve allocation. Basicly, an object in a heap is not scope
dependent, it dies when you tell it to. Meanwhile, an object on the stack is destroyed automatically when its scope ends.

The scope of memory allocated on the ’stack’ is the scope
of the enclosing block. They get destroyed when the enclosing
block is finished. Thats why they are called ‘auto’ objects.

Example:

{
int i;

} // block ends, i gets destroyed

The scope of memory allocated on the ‘heap’ is different. Objects
get allocated with new (or malloc) and get destroyed when a corresponding
delete (or free) is executed. Blocks do no longer influence the scope of
these objects.

Example:

int* pJ;

{
int* pI = new int [20];

// Note that 2 things are happening here:
// 1.) An int array is allocated on the free store (aka heap).
// This array will be there until a corresponding delete [] is
// executed
// 2.) A variable pI is created. Since pI was not dynamically created
// with new or malloc, it is an auto object (created on the stack)
// Thus the enclosing block determines its lifetime

pJ = pI;

} // block ends. pI gets destroyed, but not so the int array. It
// will stay there in memory until a delete is done.

delete [] pJ; // now the memory in the free store (aka heap) gets released.

Free store allocation usually takes more time

Related Posts:

  • No Related Posts

-- Sponsered Links --