C++ bug in structure packing and inheritance

Daniel Berlin dan@cgsoftware.com
Sat Dec 15 16:09:00 GMT 2001



On Sat, 15 Dec 2001, Sam Lantinga wrote:

> There seems to be a bug in structure packing in that if you have
> two classes or structures that both inherit from a class with no
> data members, then they will be the wrong size.

> A simple example follows:
>
> #include <stddef.h>
> #include <stdio.h>
>
> struct a {
> };
>
> struct b : public a {
> 	float x;
> 	float y;
> };
>
> struct c : public a {
> 	b data;
> 	float z;
> };
>
> main()
> {
> 	printf("size of a = %d (should be 0)\n", sizeof(a));
> 	printf("size of b = %d (should be 8)\n", sizeof(b));
> 	printf("size of c = %d (should be 12)\n", sizeof(c));
> 	printf("offset of c.z = %d (should be 8)\n", offsetof(c,z));
> }
>
> Sample output with the current CVS of gcc is:
> size of a = 1 (should be 0)
> size of b = 8 (should be 8)
> size of c = 16 (should be 12)
> offset of c.z = 12 (should be 8)
I have no idea whether it's correct, but i can tell you *why* it happens.
-fclass-hierarchy-dump shows:

Class a
   size=1 align=1
a (0x3015d500) 0 empty

Class b
   size=8 align=4
b (0x3015d7c0) 0
  a (0x3015d800) 0 empty

Class c
   size=16 align=4
c (0x3015db00) 0
  a (0x3015db40) 0 empty


If you force it to pack them (__attribute__ packed or whatever), you'll
get:
size of a = 1 (should be 0)
size of b = 8 (should be 8)
size of c = 13 (should be 12)
offset of c.z = 9 (should be 8)

And the class-hierarchy-dump will show:
Class a
   size=1 align=1
a (0x3015d500) 0 empty

Class b
   size=8 align=1
b (0x3015d800) 0
  a (0x3015d840) 0 empty

Class c
   size=13 align=1
c (0x3015db40) 0
  a (0x3015db80) 0 empty


I dunno whether the empty base class should have size=0 align=0, but if
it did, this should cause the others to do what you expect.

>
> If this is correct, I would appreciate it if somebody could explain it.
>
> Thanks,
> 	-Sam Lantinga, Software Engineer, Blizzard Entertainment
>



More information about the Gcc mailing list