The Wayback Machine - https://web.archive.org/web/20211010092432/https://www.geeksforgeeks.org/g-fact-30/
Skip to content
Related Articles

Related Articles

Improve Article

delete and free() in C++

  • Difficulty Level : Easy
  • Last Updated : 17 Feb, 2021

In C++, delete operator should only be used either for the pointers pointing to the memory allocated using new operator or for a NULL pointer, and free() should only be used either for the pointers pointing to the memory allocated using malloc() or for a NULL pointer.

The most important reason why free() should not be used for de-allocating memory allocated using NEW is that, it does not call the destructor of that object while delete operator does.

Take a step-up from those "Hello World" programs. Learn to implement data structures like Heap, Stacks, Linked List and many more! Check out our Data Structures in C course to start learning today.

CPP




#include<stdio.h>
#include<stdlib.h>
int main()
{
    int x;
    int *ptr1 = &x;
    int *ptr2 = (int *)malloc(sizeof(int));
    int *ptr3 = new int;
    int *ptr4 = NULL;
 
    /* delete Should NOT be used like below because x is allocated
        on stack frame */
    delete ptr1; 
 
    /* delete Should NOT be used like below because x is allocated
        using malloc() */
    delete ptr2; 
 
    /* Correct uses of delete */
    delete ptr3;
    delete ptr4;
 
    getchar();
    return 0;
}

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

My Personal Notes arrow_drop_up
Recommended Articles
Page :