The easy solution is to use smart pointers. If you really want for “copies” of your pointer to also be nullified use a combination of shared_ptr and weak_ptr.

Changing the delete operator to take a reference to a pointer will break things. Yes, you could recompile and have it work, but if you have an existing library that calls the old delete operator and link in a new C++ standard library that only provides the new delete operator, you get a link error because the signature has changed. This is on top of the things others have mentioned.

One of the major goals of C++ is not to break old code (if not absolutely necessary). This proposal would not have any chance of succeeding.

Concerning low-level code: It too should use at least std::unique_ptr instead of raw pointers. With just some minimal support for function inlining it is as efficient as what you are proposing. shared_ptr has some overhead, but unique_ptr doesn’t.

The feature you want could just be a compiler flag. It does not have to be standardized to be able to do this. A static analyzer could also look for places in the code where a delete is not immediately followed by zeroing the pointer. One big exception for this is destructors: zeroing the pointer inside the destructor can (and will) be optimized out because the lifetime of the object containing the pointer has ended.

On Aug 23, 2025, at 5:04 AM, organicoman via Std-Proposals <std-proposals@lists.isocpp.org> wrote:


Hello,
One of the recurring bugs in c++ is use after free.
I'm wondering, why the delete operator doesn't take the pointer parameter by reference and nullify it?
So instead of
void operator delete(void* p);
It becomes 
void operator delete(void* &p);
And it assigns the value nullptr to p after freeing its corresponding memory.
Look at this example:
---------
{
  int* p = new int(42);
  int* const& to_p = p; // as a guideline
  delete p; // if taken by reference an nullified
  *p; // this will be a guaranteed runtime error
  *to_p; // and all previous copies obey too
}
---------
On top of that, basically we need just to add a guideline that mandate:
-All duplication of a pointer should be by reference if modifying, or const reference if not.
So it is guaranteed that if you free the memory using any of the references,  all copies will be nullptr.

So, is there any constraints to prevents this other than breaking old code?

Regards



Sent from my Galaxy

--
Std-Proposals mailing list
Std-Proposals@lists.isocpp.org
https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals