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.
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.
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