Reputation: 1636
Is there anyway to make gcc pad only at the end of a packed structure?
I am using a packed structure for space optimization, but also use that struct to compute memory offsets (storing multiple structs in a buffer). Therefore if the total size of my struct is not aligned (not a multiple of 4 let's say), if I try to access the following struct in my buffer I will get a SIGBUS.
E.g.
sizeof(my_packed_struct) == 11
sizeof(other_struct) == 12
If I put a my_packed_struct at address 0x2000, I would also put other_struct at 0x200B (+11 bytes).
So if I want to access the other_struct, e.g. (other_struct*)0x200B, I would get a SIGBUS.
So I'm curious if there's a way to make GCC pad the structure to avoid this problem.
Here is the definition:
typedef struct __attribute__ ((packed)) my_packed_struct {
uint8_t att1;
bool att2;
uint32_t att3;
uint32_t att4;
bool att5;
} my_packed_struct;
I could just add an attribute like
typedef struct __attribute__ ((packed)) my_packed_struct {
uint8_t att1;
bool att2;
uint32_t att3;
uint32_t att4;
bool att5;
uint8_t pad;
} my_packed_struct;
To make sure to match to size 12, but I'm looking for a solution where I wouldn't have to compute the size and pad manually (e.g. if I have to add another attribute in the future).
I had a look at memory alignment within gcc structs, I do store the struct in a buffer internally, but I still need to expose a struct for convenience and client use.
Upvotes: 3
Views: 594
Reputation: 1516
What about this trick
union __attribute__ ((packed)) struct_union
{
struct my_packed_struct data;
int pad[(sizeof(my_packed_struct)+3)/sizeof(int)];
} struct_union;
and use struct_union instead of my_packed_struct directly?
Why it will work?
Upvotes: 1