How to detect if a pointer was deleted and securely delete it?
c++, memory-management, pointers
Solution
There can be three solutions. You might want to choose one depending on the effort/quality ratio you want to acheive:
Elegant and most correct solution:
Use smart pointers and you do not have to manually call `delete` ever again. This is the best possible way to overcome this problem. It utilizes the principle of RAII which works perfectly for a language like C++ which does not have an in-built garbage collector.
Less elegant but workable solution:
Assign the pointer to `NULL` after deletion. Calling `delete` on a `NULL` pointer is a no-op so it removes the need to have that extra `NULL` check but this might hide some problems instead of making them visible.
Less elegant but more correct solution:
Hunt down all the multiple `delete` problems by letting your program crash. You might as well use memory analyzer programs like valgrind and then fix your code to avoid all these problems.
Problem
In C++ How to decide or know if a pointer was deleted before?? when i tried to delete a pointer that was previously deleted in another part of the code it threw an exception that can't be handled. I was wondering if there is a way to check or try delete the pointer ? any reference about advanced memory operations. also i want to master the un-handled exceptions of pointers and the access to protected or access is violation ,... this kind of error. thanks for those who give some of their knowledge and their time to help other people and share their benfits Update The big advice from a lot of modern c++ developers community is - Use smart pointers or try to avoid the use of raw pointers. But for throw security and insuring free of memory (ISO_CPP_FAQ) and of course if you want to avoid the small overhead of using smart pointers[may not be noticeable always but they have overhead] you can write your custom methods that deal with raw pointers [type*] - this is not general. Prefer always smart pointers to raw pointers. In 'Going Native 2013' a common advice given was - Never use raw pointers.