On 2023-02-17 06:24, Jonathan Wakely wrote:
Please be aware that in C++ it's implementation-defined, not undefined.
That means that an implementation without trap representations for
pointers can choose to make it behave just like using (uintptr_t)p.
https://cplusplus.github.io/CWG/issues/1438.html
<https://cplusplus.github.io/CWG/issues/1438.html>
https://cplusplus.github.io/CWG/issues/623.html
<https://cplusplus.github.io/CWG/issues/623.html>
https://cplusplus.github.io/CWG/issues/616.html
<https://cplusplus.github.io/CWG/issues/616.html>
https://cplusplus.github.io/CWG/issues/312.html
<https://cplusplus.github.io/CWG/issues/312.html>
We could still warn in C++ (because the code isn't portable) but I would
strongly suggest we don't influence C++ codegen based on deallocated
pointers being undefined. I don't think gcc supports any targets with
trapping pointers, and there are quite enough sources of UB already. We
don't need to create traps for users where there are no traps for
pointers :-)
The codegen problem is a pointer provenance issue and AFAICT,
-Wuse-after-free=3 is also framed in that context and not as a problem
with simply taking the numeric value of the pointer to, e.g. log it
somewhere.
More concretely, something like this is what causes problems:
Foo *old = malloc (sz);
...
Foo *new = realloc (old, newsz);
if (new != old)
{
old = new;
/* Adjust references. */
}
/* Otherwise continue using old unchanged */
...
The problem is the assumption that the old pointer continues to be valid
because it has the same numeric value as the new one. This is not an
uncommon code pattern in C, what about C++?
On a fat pointer-like scheme such as the Arm Morello cpu, this won't
work at all because even though old and new have the same numeric
values, old will have been invalidated.
Sid