Date: Sun, 27 Jul 2025 19:29:25 +0100
On Sun, Jul 27, 2025 at 2:11 AM Breno GuimarĂ£es wrote:
>
> Compile with -O2 and you will see that it prints 0
Just to clarify what's going on here . . . When the compiler
encounters the assignment to "p" in the destructor, it sees that the
variable "p" isn't read from again before "*this" is destroyed, so the
assignment is optimised away. You can disable the optimisation by
changing the following line:
p = . . . .
into:
const_cast<decltype(p) volatile &>(p) = . . . .
Of course this doesn't change the fact that the C++26 Standard says
that an object's bytes are unspecified after the object dies, but
still it keeps us sane to understand why the compiler's doing what
it's doing.
So far I think David Brown's idea is the best, he wrote:
> const int deadbeaf { };
> const void * badptr { &deadbeaf };
> Then when you start your debugger, put a data watchpoint (read/write
> access) on the symbol "deadbeaf". Any time your code tries to access
> that address, your debugger halts the code.
I think David's idea, combined with Address Sanitizer, would be a
winner, because it would also catch instances where the address of
'badptr' is incremented and dereferenced. It might be an idea to
"build this into" the compiler and debugger, and to standardise the
nomenclature in the C++ standard (i.e. 'badptr_t' and 'badptr').
>
> Compile with -O2 and you will see that it prints 0
Just to clarify what's going on here . . . When the compiler
encounters the assignment to "p" in the destructor, it sees that the
variable "p" isn't read from again before "*this" is destroyed, so the
assignment is optimised away. You can disable the optimisation by
changing the following line:
p = . . . .
into:
const_cast<decltype(p) volatile &>(p) = . . . .
Of course this doesn't change the fact that the C++26 Standard says
that an object's bytes are unspecified after the object dies, but
still it keeps us sane to understand why the compiler's doing what
it's doing.
So far I think David Brown's idea is the best, he wrote:
> const int deadbeaf { };
> const void * badptr { &deadbeaf };
> Then when you start your debugger, put a data watchpoint (read/write
> access) on the symbol "deadbeaf". Any time your code tries to access
> that address, your debugger halts the code.
I think David's idea, combined with Address Sanitizer, would be a
winner, because it would also catch instances where the address of
'badptr' is incremented and dereferenced. It might be an idea to
"build this into" the compiler and debugger, and to standardise the
nomenclature in the C++ standard (i.e. 'badptr_t' and 'badptr').
Received on 2025-07-27 18:29:36