I was wondering if there is a possibility to catch errors like this in C++:
object* p = new object;
delete p;
delete p; // This would cause an error, can I catch this?
I know I could set the pointer p
to NULL
after the first object deletion. But just imagine you wouldn't do that.
I don't think you can catch this kind of error because I think the result is undefined behaviour. It might do nothing, it might crash, it might just corrupt the memory and cause a problem later down the line.
If you found it did something specific with your current compiler you could try and handle that, but it might do different things in debug and release, and different again when you upgrade the compiler version.
Setting the pointer to null has been suggested, but I think you would be better off using smart pointers and not deleting them at all.
Why no one wants to use smart pointers like boost::shared_ptr
? If you use it, you can forget delete
-operator. ;)
Unfortunately I can't speak for the windows world, but I know there are some tools in the unix world that does this for you (in runtime)
The idea is to implement the memory allocation functions together with some extra checks. The library can the be told to abort the process when a problem is found and you can find the problem by looking at the stack trace. libumem on solaris is one example of this.
I am sure there must be similar things on the windows platform.
There are other tools that does static code analysis, which will help you find the problems before you run the code. Coverity is one example, and I think it works on windows as well. We've managed to find quite a few potential problems with coverity. Unfortunately, it isn't free. Evaluation versions should be possible though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With