Does this C inheritance implementation affect undefined behavior?

struct parent { char a; char b; }; struct child { struct parent parent; int c; char d; }; struct grandchild { struct child child; long e; }; void print_parent_val(struct parent *p) { printf("%d\n", p->a); } int main (int argc, char **argv) { struct grandchild g; g.child.parent.a = 69; print_parent_val((struct parent *)&g); return 0; } 

The program compiles (without warning) and works fine and prints 69 as expected. I have never seen code that implements this inheritance technology, so I really hesitate to see this as "OK."

EDIT: How about turning a grandson into a child? Is transformation of the middle generation possible?

 void print_parent_val(struct child *c) { printf("%c\n", c->d); } int main (int argc, char **argv) { struct grandchild g; g.child.parent.a = 69; g.child.d = 'w'; print_parent_val((struct child *)&g); return 0; } 
+7
c language-lawyer struct
source share
1 answer

As I see, there is no undefined behavior area here.

Citation C11 , chapter Β§6.7.2.1, Qualifiers of structure and union, (emphasis added)

Inside the structure object, non-bit fields and units in which bit fields have addresses that increase in the order in which they are declared. A pointer to a structural object, appropriately transformed, points to its initial member (or if this member is a bit field, then to the block in which it is located) and vice versa. There may be an unnamed padding inside the structure object, but not at the beginning.

So, with the current snippet (and approach) you should be good to go.

+7
source share

All Articles