Monday, 25 August 2014

Why stack and heap are necessary ?

Why stack and heap both are necessary?

Both has its unique features. Stack is more efficient for allocating and deallocating the memory. Then you may ask whats the need for the heap.

Although heap is slower in allocation and deallocation of memory, heap as a unique feature that it can be allocated and deallocated at any place the programmer wish.

Consier the following example:

int *a=new int(10000000);
float *b=new  float(1);

In the above case, either a or b can be deallocated first based on the need. But in the case of stack it will deallocate in orderly fashion

Where the memory for pointer variable will be allocated?

It is allocated on the stack. (Remember it is Pointer variable not the dynamic memory allocated)