Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I catch bad pointer errors in C++?

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?
  1. Can I check if the pointer is valid?
  2. Can I catch some exception?

I know I could set the pointer p to NULL after the first object deletion. But just imagine you wouldn't do that.

like image 313
Simon Avatar asked Jun 18 '10 07:06

Simon


3 Answers

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.

like image 84
David Sykes Avatar answered Oct 05 '22 23:10

David Sykes


Why no one wants to use smart pointers like boost::shared_ptr? If you use it, you can forget delete-operator. ;)

like image 28
LonliLokli Avatar answered Oct 06 '22 01:10

LonliLokli


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.

like image 31
Mattias Nilsson Avatar answered Oct 06 '22 00:10

Mattias Nilsson