Search code examples
cgccattributesmemory-alignment

GNU GCC compiler - aligned attribute


I correctly got the alignment warning

cast increases required alignment of target type [-Wcast-align]

from the GCC compiler due to the following code:

uint8_t array[100];

uint32_t foo;
foo = * ( (uint32_t *) &array[10]);

Then I used the aligned attribute to figure out the issue:

uint8_t array[100] __attribute__ ((aligned(4)));

uint32_t foo;
foo = * ( (uint32_t *) &array[10]);

Despite this trick I however got the same warning. Is that normal or the warning should disappear?


Solution

  • Think about it: &array[10] won't be 4 byte aligned even with __attribute__ ((aligned(4))), since you are looking at an offset of 10 bytes into a 4 byte aligned array. So you will only be getting 2 byte alignment in this example, and gcc is correct to emit a warning. Try it with an index of say 12, instead of 10, and the warning might go away.