Sujet : Re: Regarding assignment to struct
De : david.brown (at) *nospam* hesbynett.no (David Brown)
Groupes : comp.lang.cDate : 06. May 2025, 10:35:30
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vvcl52$2lank$1@dont-email.me>
References : 1 2 3 4 5 6 7 8 9
User-Agent : Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Thunderbird/102.11.0
On 05/05/2025 22:27, Keith Thompson wrote:
Andrey Tarasevich <noone@noone.net> writes:
[...]
#include <stdio.h>
>
struct S { int a[10]; };
>
int main()
{
struct S a, b = { 0 };
int *pa, *pb, *pc;
>
pa = &a.a[5],
pb = &b.a[5],
pc = &(a = b).a[5],
printf("%p %p %p\n", (void *) pa, (void *) pb, (void *) pc);
}
>
This version has no UB.
I believe it does. pc points to an element of an object with
temporary lifetime. The value of pc is then used after the object
it points to has reached the end of its lifetime. At that point,
pc has an indeterminate value.
N3096 6.2.4p2: "If a pointer value is used in an evaluation after
the object the pointer points to (or just past) reaches the end of
its lifetime, the behavior is undefined. The representation of a
pointer object becomes indeterminate when the object the pointer
points to (or just past) reaches the end of its lifetime."
It seems clear to me that "pc" has an indeterminate value after the expression assigning, since it points to an object with temporary lifetime.
And attempting to use the value of an object with automatic storage while it has an indeterminate value is undefined behaviour.
As far as I can see, simply reading the value in "pc" to print it out is UB according to the C standards. It is clearly going to be a harmless operation on most hardware, but there are processors where pointer registers are more complicated than simple linear addresses - they can track some kind of segment structure describing the range of a data block, or permissions for access to the data, and such structures could have been deactivated or deallocated when the temporary lifetime object died. Even attempting to read the value of the pointer, without dereferencing it, would then cause some kind of fault or trap.