Skip to main content

Dynamic memory allocation (Heap) vs Stack



new and delete operators

   When we use new & delete operators in our program the heap memory (application memory) is being dynamically allocated. The allocated heap memory is used to store values and those memory is pointed by the pointers in the stack.

    In pointers the new operator is dynamically allocates memory and assign a pointer variable to the start of that memory location.

                    syntax:             new datatype;

In the following example the new operator allocates memory dynamically and returns it address to the pointer variable pi. To access the stored values from the pointer location we use dereference(*) operator.

              int *pi= new int;        //pi=500
                       *pi=5;                          // storing value 5 in the pointer location 500
                       cout<< pi << *pi;        //where pi=500 and *pi=5


Dynamic memory is allocated in heap(application memory). And its addresses are stored in stack by the pointer.

Once we used the memory. We have to deallocate it
         delete – used to deallocate dynamically. 
         delete pi;

What happens if the allocated memory is not released

  1. Garbage value in the heap.

Here once the pointer p is allocated with a new value 10. So its address 700 is overwritten in this pointer p.  the value in the heap address 500 is no longer referenced. So before reassigning new values to the pointer we have to free up its value using delete keyword.

Garbage value in the heap

Dangling pointer

The delete operator deletes the value that are pointed by the sepcified pointer. 

     (e.g)   delete p;

It only deletes the value from the heap which was pointed by the pointer p. It does not delete the pointer from the stack. It is unnecessarily points the location 500.

Solution to the dangling pointer

So, once the value is deleted. The pointer must be assigned with either 0 or NULL.

ii. Garbage collection

Whenever the heap memory is dynamically allocated in the program that should be freed up before the end of the program.

In this case the memory is allocated to the pointer p. but the memory is not freed up before the function ends. If a pointer is declared and initialized inside a method. It should be freed up before the end of the function.
used to allocate memory dynamically, returns address of the memory. That’s why we use pointer to catch that address.

    void x()
    {
       int *p=new int();
       delete p;
       p=NULL;
    }

Here before the function x() finishes the pointer p is freed up at the end of the function, So it's value popped out from the stack and the assigned heap memory 500 is no longer referenced.

Comments