1
struct NodeUsingAttribute
{

char cr;
int data __attribute__((aligned(8)));

};


struct Node
{

char cr;
int data ;

};

The first one gives size as 16 and second on gives size as 8 on my machine. I am not able to figure out why 16?.

Anup Buchke
  • 5,210
  • 5
  • 22
  • 38

1 Answers1

4

Your aligned attribute requires the data element to be on an 8-byte boundary. To ensure that all elements of an array of the structure are properly aligned, the structure as a whole has to be 8-byte aligned, and that's achieved by making it 16 bytes long.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • Thanks Jonathan. So do you mean that, ideally for one instance the size should be 12. But incase of only array to be aligned the compiler makes it 16 bytes, so that successive elements are properly aligned – Anup Buchke Apr 30 '14 at 17:38
  • 1
    The size of a structure is fixed at compile time, barring flexible array members which are not part of this question, thank goodness. The size, therefore, has to be such that it will work in all contexts: as a singleton structure, as an element of an array of the structure type, as an element of another structure or a union. To achieve all that and have a single size, the size must be 16 bytes (1 byte for the `cr` member, 7 bytes padding, 4 bytes for the `data` member, and 4 bytes padding). Now the compiler can ensure that it will be properly aligned everywhere it can be used. – Jonathan Leffler Apr 30 '14 at 17:41
  • 1
    Using a size of just 12 bytes would not ensure that the structure is properly aligned when used in an array, because the elements of an array are densely packed (contiguous -- no gaps). – Jonathan Leffler Apr 30 '14 at 17:42