Issues with Pointers (delete) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 13

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?

17th Jul 2017, 6:31 AM
Hatsy Rei
Hatsy Rei - avatar
3 Answers
+ 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
17th Jul 2017, 7:05 AM
aklex
aklex - avatar
+ 8
In my experience, deleting a pointer won't set it to null, you have to set it to null explicitly.
17th Jul 2017, 9:35 AM
Bàng Tứ Cường
Bàng Tứ Cường - avatar
+ 5
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; } }
17th Jul 2017, 9:09 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar