#1181 sizeof doesn't return good value

closed-invalid
nobody
gcc (462)
2008-06-27
2008-06-26
cacao cocoa
No

//a basic exemple of the bug

#include <stdio.h>

struct _s{
char c;//normaly 1 Byte
int i;//normaly 4 Bytes
};

printf("size char:%d\n", sizeof(char));// shoud be a size of 1 Byte
printf("size int:%d\n", sizeof(int));// shoud be a size of 4 Bytes
printf("size:%d\n", sizeof(struct _s));//shoud be a size of 4+1=5 Bytes in fact it prints 8.

//yes sizeof(struct _s) doesn't give the good value

/***
I found this bug with in many gcc i tried
particulary on
gcc version3.4.2 on windows XP SP2
gcc version 3.4.5 mingw-vista special r3
and the bug is non platform dependant.
***/

Discussion

  • Bengt Werstén

    Bengt Werstén - 2008-06-27

    Logged In: YES
    user_id=2122959
    Originator: NO

    This is no bug. The field i needs to be aligned to 4 byte and since c is of size 1 byte an extra 3 bytes will be used for padding in between.

     
  • Aaron W. LaFramboise

    Logged In: YES
    user_id=1040098
    Originator: NO

    bengtwersten is correct.

    sizeof returns the size of the object including alignment, and on x86, ints are aligned to 4-byte boundaries.

    It is possible to tell GCC to pack the struct or otherwise alter the layout. See -fpack-struct and the 'aligned' and 'packed' attributes in the GCC manual.

     
  • Aaron W. LaFramboise

    • status: open --> closed-invalid
     

Log in to post a comment.

Get latest updates about Open Source Projects, Conferences and News.

Sign up for the SourceForge newsletter:

JavaScript is required for this form.





No, thanks