Operator delete

From Wikipedia, the free encyclopedia

In the C++ programming language, the delete operator returns memory alloctated by new back to the heap. A call to delete must be made for every call to new to avoid a memory leak. After calling delete the memory object pointed to is invalid and should no longer be used. Many programmers assign NULL to pointers after using delete to help minimize programming errors.

Example code snippet:

    int *p_var = NULL;     // new pointer declared
    p_var = new int;       // memory dynamically allocated
    
    /* .......
    other code
    ........*/
    
    delete p_var;          // memory freed up
    p_var = NULL;          // pointer changed to NULL

Arrays allocated with new can be similarly deallocated with delete []:

    int size = 10;
    int *p_var = NULL;     // new pointer declared
    p_var = new int [size];// memory dynamically allocated
    
    /* .......
    other code
    ........*/
    
    delete [] p_var;       // memory freed up
    p_var = NULL;          // pointer changed to NULL