[Bug c/51628] __attribute__((packed)) is unsafe in some cases
hjl.tools at gmail dot com
gcc-bugzilla@gcc.gnu.org
Thu Nov 2 13:14:00 GMT 2017
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=51628
--- Comment #33 from H.J. Lu <hjl.tools at gmail dot com> ---
[hjl@gnu-skl-1 gcc]$ cat x.c
#include <stdio.h>
#include <stddef.h>
typedef int aligned_int __attribute__((warn_if_not_aligned(4)));
int main(void)
{
struct foo {
char c;
aligned_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;
}
[hjl@gnu-skl-1 gcc]$ ./xgcc -B./ -S x.c -Wall
x.c: In function \u2018main\u2019:
x.c:9:5: warning: alignment 1 of \u2018struct foo\u2019 is less than 4
[-Wif-not-aligned]
} __attribute__((packed));
^
x.c:8:14: warning: \u2018x\u2019 offset 1 in \u2018struct foo\u2019 isn't
aligned to 4 [-Wif-not-aligned]
aligned_int x;
^
[hjl@gnu-skl-1 gcc]$
More information about the Gcc-bugs
mailing list