c++pointersdouble-pointer

Right way to delete pointer to pointer in C++


I have this simple example which fails in "delete poinerToBufferPointer":

char* buffer = new char[8];
memset(buffer, 1, 8);
char** poinerToBufferPointer = &buffer;
delete poinerToBufferPointer;
delete[] buffer;

But if I comment the "delete poinerToBufferPointer"

char* buffer = new char[8];
memset(buffer, 1, 8);
char** poinerToBufferPointer = &buffer;
//delete poinerToBufferPointer;
delete[] buffer;

it's working but the question is who will delete the double pointer? Also very strange behavior is when I do delete on the pointer only it fail on delete[] buffer.

char* buffer = new char[8];
memset(buffer, 1, 8);
char** poinerToBufferPointer = &buffer;
delete *poinerToBufferPointer;  // <--- only delete the pointer that points 
delete[] buffer;

What is going on in memory, and what is the right way to delete both pointers?


Solution

    1. You do not delete pointers, you delete the thing a pointer points to.
    2. You only need to delete things you allocate with new

    delete[] buffer; deletes the array pointed to by the pointer buffer. Since you allocated that with new[] that is correct.

    delete pointerToBufferPointer; attempts to delete the pointer pointed to by pointerToBufferPointer. You did not allocate that pointer using new, however, so that is incorrect. A program that attempts to do that has undefined behavior.

    If you had allocated the pointer pointed to by pointerToBufferPointer using new then you would need to delete it. For example, the following is correct (though you should almost never need to write code like this):

    char** pointerToBufferPointer = new char*;
    *pointerToBufferPointer = new char[8];
    // ...
    delete[] *pointerToBufferPointer;
    delete pointerToBufferPOinter;
    

    In most real code you should avoid using new and delete directly at all. For most common use cases, containers like std::string and std::vector that manage their own memory allocation for you are perfectly sufficient and much less error-prone.