3

I thought the "aligned" attribute will always be respected. But I tried the code sample below, and the output was "16 19". I was expecting "16 24". I used g++. Why the compiler ignored the "aligned" attribute in this case? Does "packed" take precedence over "aligned"? Is there a way to make sure Test1 is always properly aligned to 8?

typedef unsigned char uint8;
typedef unsigned int uint32;
typedef unsigned long long uint64;

class Test1
{
public:
   uint8 t1;
   uint64 t2;
}  __attribute__ ((aligned(8)));

class Test2
{
private:
   uint8 t1;
   uint8 t2;
   uint8 t3;
   Test1 t4;
} __attribute__ ((packed));


int
main(int argc, char **argv)
{
   Test1 t1;
   Test2 t2;    
   printf("%ld %ld\n", sizeof(t1), sizeof(t2));
}
MSalters
  • 173,980
  • 10
  • 155
  • 350
yacc45
  • 121
  • 5
  • Is there a way to make sure Test1 is always properly aligned to 8? you can always `assert(((int)&t1) % 8 == 0)`. Will break at runtime. – Jean-François Fabre Aug 25 '16 at 22:14
  • yes, but I need a solution that doesn't break at run-time. – yacc45 Aug 25 '16 at 22:31
  • Might help? http://stackoverflow.com/questions/841433/gcc-attribute-alignedx-explanation – Fantastic Mr Fox Aug 25 '16 at 23:50
  • This is GCC, I assume? – MSalters Aug 26 '16 at 08:01
  • 2
    It is ignoring the alignment requirement for Test1. Seems reasonable when you say "ignore alignment and pack tightly", a struct isn't treated differently from an uint64. Fix it by inserting a dummy field that takes enough space. Or omit the attribute completely, also gives you what you want. – Hans Passant Aug 26 '16 at 08:57
  • Yes, this is GCC (g++ to be more exact). – yacc45 Aug 26 '16 at 20:20
  • Let's assume that I have directly control of Test1. But Test2 is shared by many developers and thus things like manual padding may not be ideal. To me "aligned" is a correctness issue. If read of Test1->t2 takes multiple instructions, it will cause atomic issues. On the other hand, "packed" is a performance optimization that may save some memory space. So I am surprised that GCC respect "packed" more than "aligned". – yacc45 Aug 26 '16 at 20:24

0 Answers0