[Bug c++/106965] g++ optimization removes assigning 0 to deleted pointer- causes double free.

olddra3rd at mozmail dot com gcc-bugzilla@gcc.gnu.org
Tue Sep 20 10:02:33 GMT 2022


https://gcc.gnu.org/bugzilla/show_bug.cgi?id=106965

--- Comment #4 from Boaz <olddra3rd at mozmail dot com> ---
(In reply to Jonathan Wakely from comment #3)
> (In reply to Richard Biener from comment #1)
> > I think it's undefined to invoke a DTOR twice which is what you do here. 
> > After the DTOR the m_ptr member becomes undefined so re-evaluating that in
> > the second invocation (when there's no object of type X anymore) is
> > undefined.
> 
> Right, and because you can't ever use the m_ptr member after the destructor,
> there's no point writing the 0 to it. That's a dead store, so the compiler
> is allowed to eliminate it. A correct program can never observe whether that
> store happened or not.

My logic in assigning 0 was preventing delete on a dangling pointer in case of
a double call to a destructor (for example, if the object was dynamically
allocated) which is a good practice as far as I know.

But my mistake was indeed calling a destructor explicitly on an automatic
storage, quoting from ISO2020:

"If a variable with automatic storage duration has initialization or a
destructor with side effects, an implemen-
tation shall not destroy it before the end of its block nor eliminate it as an
optimization, even if it appears to
be unused, except that a class object or its copy/move may be eliminated as
specified in 11.10.6."

So... my bad.


More information about the Gcc-bugs mailing list