Re: Questions about pointers to objects and pointers to functions



"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.
.



Relevant Pages

  • Re: ctime double double check
    ... with converting the time. ... However I couldn't find anything in the standard that specifies ... how the struct tm - time_t conversions should be done which means ... storing date as a string of characters and it may look like in ...
    (comp.lang.c)
  • Re: [PATCH] draft patch to make usr.bin/kdump WARNS?= 6 clean
    ... usr.bin/kdump as a likely 'victim' for converting from WARNS?= 0 to ... Fix a signed vs unsigned comparison with a simple cast because the ... ia64 assigning a struct sockaddr value to either struct sockaddr_in or ... Fix a shadowed declaration for flags by renaming a locally scoped ...
    (freebsd-hackers)
  • [PATCH] draft patch to make usr.bin/kdump WARNS?= 6 clean
    ... usr.bin/kdump as a likely 'victim' for converting from WARNS?= 0 to ... Fix a signed vs unsigned comparison with a simple cast because the ... ia64 assigning a struct sockaddr value to either struct sockaddr_in or ... Fix a shadowed declaration for flags by renaming a locally scoped ...
    (freebsd-hackers)
  • Re: [PATCH] Fix proc_file_write missing ppos update
    ... You'd better start converting to struct file_operations::write now. ... someone who understands the specific driver code better should ... struct proc_dir_entry *parent, ...
    (Linux-Kernel)
  • Re: Rallocating a struct * *
    ... > Following shows allocation of my struct: ... After converting your code to C, I was able to realloc 45 ...
    (comp.lang.c)