Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ throw exception when deleting invalid address

Tags:

c++

exception

I'm making a custom allocator and I know when the application tries to deallocate an invalid address but I don't know what exception should I throw. For example:

...
int *a=new int;
delete a;
delete a;
...

When the second delete happens I know that I don't have that address allocated in my memory pool and I need to throw an exception for the user to know that at some point in the program he tried to deallocate an invalid address.

like image 827
Ovidiu Firescu Avatar asked Dec 21 '25 03:12

Ovidiu Firescu


1 Answers

No operator delete is allowed to throw any exception. Throwing an exception from an operator delete causes undefined behavior. See [basic.stc.dynamic.deallocation]/3.

Even if you could diagnose double-deletes this way, using delete a; twice still causes undefined behavior. This is unavoidable, for example because delete a; also calls the destructor first and you are generally not allowed to call the destructor twice on an object.

And even that aside, calling operator delete twice on the same pointer without intervening allocation still causes undefined behavior, because the first operator delete call ends the storage duration of the allocated memory, making the pointer value invalid, and passing an invalid pointer value to any deallocation function causes undefined behavior, see [basic.stc]/4.

The only thing you can do when a user tried to double delete a pointer is to abort the program, e.g. by a call to std::abort. This is probably the best course of action, since undefined behavior already happened and so continuing the program would be pointless or even a security risk.

like image 114
walnut Avatar answered Dec 23 '25 15:12

walnut