Monday, 17 November 2014

Difference between delete and free() in C++ with example

What is the difference between delete and free() in C++ ? 

delete operator:

delete operator is used to delete the dynamic memory allocated using new operator or for the NULL pointer.
free () is used to free the dynamic memory allocated using the function malloc or for a NULL pointer.
Below example clarifies the differences between the free and delete.


#include<stdio.h>
#include<stdlib.h>
int _tmain (int argc, _TCHAR* argv[])
{
    int iVal;
    int *iiPtr = &iVal;
    int *iPtr2 = (int *)malloc(sizeof(int));
    int *iPtr3 = new int;
    int *iPtr4 = NULL;
    /* delete Should NOT be used like below because x is allocated
        on stack frame */
    delete iiPtr;   iiPtr = NULL;
    /* delete Should NOT be used like below because x is allocated
        using malloc() */
    delete iPtr2;  iPtr2 = NULL;
    /* deletet the memory allocated using the new */
    delete iPtr3; iPtr3 = NULL;
    delete iPtr4; iPtr4 = NULL;

    getchar();
    return 0;
}

No comments: