Re: Questions about pointers to objects and pointers to functions
- From: Tim Rentsch <txr@xxxxxxxxxxxxxxxxxxx>
- Date: 20 Sep 2005 03:24:15 -0700
"S.Tobias" <siXtY@xxxxxxxxxxxxxxxxxxxxxxxxxx> writes:
> Tim Rentsch <txr@xxxxxxxxxxxxxxxxxxx> wrote:
> > Marc Thrun <TekWarrior@xxxxxx> writes:
>
> >> struct A {
> >> int x;
> >> };
> >>
> >> and
> >>
> >> struct B {
> >> struct A y;
> >> int z;
> >> };
> [snip]
> >
> > a = (struct A*) b;
> > if( a == &b->y ) /* this 'if' will always be taken */
> >
> > You might be asking about converting the object representation
> > directly, eg, with one of
> >
> > memcpy( &a, &b, sizeof a ); /* 1 */
> >
> > a = * (struct A**) &b; /* 2 */
> >
> > Either /*1*/ or /*2*/ should also result in a usable pointer that
> > passes the 'if' test above. That is to say, to the best of my
> > understanding that is how the language in the Standard should be
> > understood.
>
> Generally, I agree, with a warning: /*2*/ is meant to express
> reinterpretation (wich is basically what /*1*/ does as well),
> but is technically UB (you're accessing the value of `b' with
> an incompatible type lvalue), and might cause real trouble in
> real world (esp. when compiler optimization is turned on).
Right, both on the technical UB and on the real potential
for problems. Thank you for pointing this out.
Rather than /*2*/ we might consider /*2'*/:
a = * (struct A *volatile *) &b; /* 2' */
Of course, this access still technically results in UB, but
it's unlikely that the access here will result in any real
world difficulties.
.
- Follow-Ups:
- References:
- Questions about pointers to objects and pointers to functions
- From: Marc Thrun
- Re: Questions about pointers to objects and pointers to functions
- From: Tim Rentsch
- Re: Questions about pointers to objects and pointers to functions
- From: S.Tobias
- Questions about pointers to objects and pointers to functions
- Prev by Date: Re: va_start problem
- Next by Date: Re: Telling an empty binary file from a "full" one
- Previous by thread: Re: Questions about pointers to objects and pointers to functions
- Next by thread: Re: Questions about pointers to objects and pointers to functions
- Index(es):
Relevant Pages
|