Skip to content

Instantly share code, notes, and snippets.

@mumbleskates
Created May 26, 2020 05:46
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 mumbleskates/17b7da5ffbd50686a3b9a4a36e5d8132 to your computer and use it in GitHub Desktop.
Save mumbleskates/17b7da5ffbd50686a3b9a4a36e5d8132 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#define ALIGNED __attribute__((aligned(32)))
// There are three structs, Foo, Bar, and Baz, each with a 20 byte field.
// Bar and Baz are annotated with an 'aligned' attribute of 32 bytes, but
// in slightly different ways.
typedef struct {
char a[20];
} Foo;
typedef struct ALIGNED {
char a[20];
} Bar;
ALIGNED typedef struct {
char a[20];
} Baz;
// They are each placed in other structs, sometimes with other values.
typedef struct {
Foo foo;
} WrappedFoo;
typedef struct {
Bar bar;
} WrappedBar;
typedef struct {
Baz baz;
} WrappedBaz;
typedef struct {
Foo foo1;
Foo foo2;
} FooFoo;
typedef struct {
Bar bar1;
Bar bar2;
} BarBar;
typedef struct {
Baz baz1;
Baz baz2;
} BazBaz;
typedef struct {
Foo foo1;
char x;
Foo foo2;
char y;
} FooxFooy;
typedef struct {
Bar bar1;
char x;
Bar bar2;
char y;
} BarxBary;
typedef struct {
Baz baz1;
char x;
Baz baz2;
char y;
} BazxBazy;
// So the question is, how are these structs laid out?
int main(int argc, char* argv[]) {
printf("Foo: %lu\n", sizeof(Foo));
printf("Bar: %lu\n", sizeof(Bar));
printf("Baz: %lu\n", sizeof(Baz));
printf("\n");
printf("WrappedFoo: %lu\n", sizeof(WrappedFoo));
printf("WrappedBar: %lu\n", sizeof(WrappedBar));
printf("WrappedBaz: %lu\n", sizeof(WrappedBaz));
printf("\n");
printf("FooFoo: %lu\n", sizeof(FooFoo));
printf("BarBar: %lu\n", sizeof(BarBar));
printf("BazBaz: %lu\n", sizeof(BazBaz));
printf("\n");
printf("FooxFooy: %lu\n", sizeof(FooxFooy));
printf("BarxBary: %lu\n", sizeof(BarxBary));
printf("BazxBazy: %lu\n", sizeof(BazxBazy));
printf("\n");
printf("Foo[3]: %lu\n", sizeof(Foo[3]));
printf("Bar[3]: %lu\n", sizeof(Bar[3]));
printf("Baz[3]: %lu\n", sizeof(Baz[3]));
}
// Possible spoiler: The below definitions are equivalent.
//
// typedef struct {
// char a[20];
// } ALIGNED Bar;
//
// typedef struct {
// char a[20];
// } Baz ALIGNED;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment