Skip to content

Instantly share code, notes, and snippets.

@Keith-S-Thompson
Created December 19, 2011 21:37
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 Keith-S-Thompson/7ccb91c3b015ec128395 to your computer and use it in GitHub Desktop.
Save Keith-S-Thompson/7ccb91c3b015ec128395 to your computer and use it in GitHub Desktop.
Demonstrating a gcc bug using __attribute__((packed)) on SPARC
#include <stdio.h>
#include <stddef.h>
int main(void)
{
struct foo {
char c;
int x;
} __attribute__((packed));
struct foo arr[2] = { { 'a', 10 }, {'b', 20 } };
int *p0 = &arr[0].x;
int *p1 = &arr[1].x;
printf("sizeof(struct foo) = %d\n",
(int)sizeof(struct foo));
printf("offsetof(struct foo, c) = %d\n",
(int)offsetof(struct foo, c));
printf("offsetof(struct foo, x) = %d\n",
(int)offsetof(struct foo, x));
printf("arr[0].x = %d\n", arr[0].x);
printf("arr[1].x = %d\n", arr[1].x);
printf("p0 = %p\n", (void*)p0);
printf("p1 = %p\n", (void*)p1);
printf("*p0 = %d\n", *p0);
printf("*p1 = %d\n", *p1);
return 0;
}
/*
Output on x86 Ubuntu, gcc 4.5.2:
sizeof(struct foo) = 5
offsetof(struct foo, c) = 0
offsetof(struct foo, x) = 1
arr[0].x = 10
arr[1].x = 20
p0 = 0xbfbab5ff
p1 = 0xbfbab604
*p0 = 10
*p1 = 20
Output on SPARC Solaris 9, gcc 4.2.1:
sizeof(struct foo) = 5
offsetof(struct foo, c) = 0
offsetof(struct foo, x) = 1
arr[0].x = 10
arr[1].x = 20
p0 = ffbff317
p1 = ffbff31c
Bus error
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment