c++ - Why is the size of packed struct 5 instead of 4 bytes here? -


see online example: ideone example

struct {   union {     struct {       uint32_t messageid : 26;       uint8_t priority : 3;      } __attribute__ ((packed));     uint32_t rawid : 29;   } __attribute__ ((packed));   uint8_t canflags : 3; } __attribute__ ((packed)) idspecial; 

why compiler report size of struct 5 bytes instead of 4 here? should contain 32 bits.

it's because of memory alignment: compiler won't start canflags in middle of byte, it'll start @ beginning of next byte (probably*). have 4 bytes initial union, , byte canflags.

if, instance, moved canflags union, (probably*) have size 4:

typedef struct structtag {   union {     struct {       uint32_t messageid : 26; /* 26bit message id, 67108864 ids */       uint8_t priority : 3; /* priority: must 0 */     } __attribute__ ((packed));     uint32_t rawid : 29;     uint8_t canflags : 3; /* <==== moved */   } __attribute__ ((packed)); } __attribute__ ((packed)) idspecial; 

updated example on ideone. obviously, specific change isn't want; i'm demonstrating issue starting new field not on byte boundary.


* "probably" because it's compiler.


Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -