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?
deletepointers, youdeletethe thing a pointer points to.deletethings you allocate withnewdelete[] buffer;deletes the array pointed to by the pointerbuffer. Since you allocated that withnew[]that is correct.delete pointerToBufferPointer;attempts to delete the pointer pointed to bypointerToBufferPointer. You did not allocate that pointer usingnew, however, so that is incorrect. A program that attempts to do that has undefined behavior.If you had allocated the pointer pointed to by
pointerToBufferPointerusingnewthen you would need todeleteit. For example, the following is correct (though you should almost never need to write code like this):In most real code you should avoid using
newanddeletedirectly at all. For most common use cases, containers likestd::stringandstd::vectorthat manage their own memory allocation for you are perfectly sufficient and much less error-prone.