+10

Issues with Pointers (delete)

While practicing binary tree implementations, I realised deallocating dynamically allocated memory using the delete keyword does not set the pointer back to NULL. The same piece of code I wrote few months ago using Code::Blocks/DevC++ is throwing exceptions on VS. IIRC, delete used to set pointers back to NULL after deallocating memory (or was it just me explicitly setting pointers back to NULL after delete? Σ(゚Д゚)). Is this a compiler issue wherein different compilers react differently?

7/17/2017 6:31:30 AM

Hatsy Rei

5 Answers

New Answer

+7

As many have pointed out, deleting a pointer does not set it to null. And if you are deleting null pointers, you have memory leaks in your code. The following example is the proper way to handle pointers we are finished with: ptr = new int; //or whatever type you need. And after use: delete ptr; //freed memory ptr = NULL; //pointed dangling ptr to NULL This is incorrect and will result in a memory leak every time: ptr = new int; And after use: ptr = NULL; //leaked memory, no pointer to above int delete ptr; //no point at all In this case, you pointed ptr at NULL, leaving behind leaked memory (the new int you allocated). You should free the memory you were pointing at. There is no way to access that allocated new int anymore, hence memory leak.

+9

It's never been the standard to null a pointer with the delete keyword. But delete is defined and implemented by the compiler's runtimes, so yes, compilers handle the delete operator differently. With Microsoft's compiler it has never nulled the pointer

+8

In my experience, deleting a pointer won't set it to null, you have to set it to null explicitly.

+6

It has never NULLed the pointer with Linux compiler either, freeing a pointer just tell the computer that the memory address in it will not be used anymore, so it removes the right to use it. Basically, it can't change the value in the variable as the pointer is passed by value. If you wanted to make it NULLed, you'll have to do something like this : void myDelete(void ** ptr){ if(ptr){ delete *ptr; *ptr=NULL; } }

+2

Well, here is quite good explanation. http://www.learncpp.com/cpp-tutorial/69-dynamic-memory-allocation-with-new-and-delete/