views:

328

answers:

4

Hi there,

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.

I am using VC++ with Visual Studio 2008/2010.

Thank you

+10  A: 

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

David Sykes
Use smart pointers- end of, really.
DeadMG
+1  A: 

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.

Mattias Nilsson
Another useful (non-free) tool is Purify. It's a runtime memory access checker, and it works really well, picking up all sorts of potential problems. If you're on Linux, there's also valgrind and efence.
Donal Fellows
+2  A: 

Why noone wants to use smart pointer like boost::shared_ptr? If you do it, you can forget delete-operator;)

LonliLokli
+1  A: 

You can catch these errors with any memory debugger such as BoundsChecker or Purify on Windows and with Valgrind on Linux.

ks1322