Skip to content

Instantly share code, notes, and snippets.

@nddrylliog
Created November 18, 2012 22:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nddrylliog/4107837 to your computer and use it in GitHub Desktop.
Save nddrylliog/4107837 to your computer and use it in GitHub Desktop.
Test struct layout by GCC
#include <stdio.h>
struct s0 {
char c1;
};
struct s1 {
char c1;
char c2;
};
struct s2 {
void *ptr;
char c2;
};
struct s3 {
char c1;
void *ptr;
char c2;
};
struct s4 {
char c1;
long double ld;
char c2;
};
int main (int argc, char **argv) {
printf("size of struct s0 = %lu\n", sizeof(struct s0));
printf("size of struct s1 = %lu\n", sizeof(struct s1));
printf("size of struct s2 = %lu\n", sizeof(struct s2));
printf("size of struct s3 = %lu\n", sizeof(struct s3));
printf("size of struct s4 = %lu\n", sizeof(struct s4));
}
@asandroq
Copy link

8
8
16
24

@nddrylliog
Copy link
Author

@asandroq Nice try! But the first two are wrong.

@nddrylliog
Copy link
Author

(At least with gcc's default options.)

@komiga
Copy link

komiga commented Nov 18, 2012

Woah, struct s4 is 48 bytes on x86_64 with GCC 4.6.3. That's the only one that threw me off.

@komiga
Copy link

komiga commented Nov 18, 2012

Also, Clang 3.1 gives the same output.

@nddrylliog
Copy link
Author

@komiga Yup! Apparently, gcc starts aligning on double-words whenever you have long double in the structure. So 3 * 16 = 48, which explains it.

Unfortunately, that means our ooc varargs bug is very hard to solve...

@nddrylliog
Copy link
Author

(And yes, actually all compilers should give the same output, except if you use -m96-bit-long-double, because otherwise it'd break the ABI.

@duckinator
Copy link

@nddrylliog

On my Pi (32bit ARM):

size of struct s0 = 1
size of struct s1 = 2
size of struct s2 = 8
size of struct s3 = 12
size of struct s4 = 24

On my desktop (64bit x86):

size of struct s0 = 1
size of struct s1 = 2
size of struct s2 = 16
size of struct s3 = 24
size of struct s4 = 48

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment