This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

RE: "sizeof" get unwanted result


Alignment is the key here as previously mentioned.
Using the packed attribute that gcc offers will force
the compiler to use the minimum space like so.

typedef struct a
{
    long data1 __attribute__ ((packed));
    unsigned short data2 __attribute__ ((packed));
    long data3 __attribute__ ((packed));

} A ;

This may be what you
want, but it does have side effects. Take your struct and 
look at the address data3 will sit at. It will always be
on a 2 byte boundary (assuming ia32 arch). This may cause
performance issues when accessing the misaligned 
member - on other architechures misaligned accesses 
are not supported by the cpu and you'll receive a 
bus error for your trouble. 

You can rearrange the members of the struct so each member
is on the correct alignment like this:

typedef struct b
{
    long data1 __attribute__ ((packed));
    long data3 __attribute__ ((packed));
    unsigned short data2 __attribute__ ((packed));
} B;

But again, this comes with caveats - if you create
an array of these structs then the alignment of subsequent
structs will be changed.



-----Original Message-----
From: Kaul, Martin [mailto:martin.kaul@leuze.de]
Sent: 19 April 2005 07:42
To: gcc-help@gcc.gnu.org
Subject: AW: "sizeof" get unwanted result




> -----Ursprüngliche Nachricht-----
> Von: gcc-help-owner@gcc.gnu.org [mailto:gcc-help-owner@gcc.gnu.org]Im
> Auftrag von Xiaoshan Sun
> Gesendet: Dienstag, 19. April 2005 04:48
> An: gcc-help@gcc.gnu.org
> Betreff: "sizeof" get unwanted result
> 
> 
> hi,
>    i use "sizeof" to get the size of a struct ,defined as:
>    typedef struct _A {
>      long data1;
>      unsigned short data2;
>      long  data3;
>    }A;
>  i guess the sizeof(A) should be 10 .however when i compile 
> and print the
> value of "sizeof(A)" ,the reult is 12!!
>  so where's the extra 2 bytes? how can i get the gcc to calculate the
> desired size ??
> an aligned issue??
On a 32bit machine the compiler align each element on a 32bit even address. So between data2 and data3 there be 2 Byte filldata. On a 64bit machine the compiler align addresses to 64bit so he fill with 6 Bytes. 

To avoid use the packed attribute as proposed by Kevin.

regards
  Martin


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]