c++ - How does compiler allocates memory to this struct? -
this question has answer here:
- structure padding , packing 8 answers
i trying use namespaces , structs & encountered issue.
c++ #include<iostream> using namespace std; namespace 1 { struct data { int val; char character; }; } namespace 2 { struct data { int val; bool boolean; }; } void functionone(void) { using namespace one; cout << "functionone()" << endl; cout << "the size of struct data : "; cout << sizeof(data) << endl; } void functiontwo(void) { using namespace two; cout << "functiontwo()" << endl; cout << "the size of struct data : "; cout << sizeof(data) << endl; } int main() { functionone(); functiontwo(); } output functionone() size of struct data : 8 functiontwo() size of struct data : 8
while when change code 'namespace two' following :
namespace 2 { struct data { char val; bool boolean; }; } output : functionone() size of struct data : 8 functiontwo() size of struct data : 2
i not able figure out how compiler allocates memory struct. in advance.
the issue here due alignment requirements. if i'm not mistaken, struct aligned based on greatest alignment requirement of it's members. in first version of struct have int; char;
. seems on machine int aligned @ 4 bytes, , compiler pads struct 3 bytes after char. in second version have bool; char;
, both 1 byte in size , aligned 1 byte (on machine) , compiler doesn't need pad size goes down 2.
i specified "on machine" because can vary based on several factors.
let's make pretty graph!
// one::data (version 1) 0 4 5 7 [int (size 4), char (size 1), padding (size 3)][...] // because of alignment restrictions on int, needs padding of 3 bytes // two::data (version 1) 0 4 5 7 [int (size 4), bool (size 1), padding (size 3)][...] // because of alignment restrictions on int, needs padding of 3 bytes // one::data (version 2), no change // two::data (version 2) 0 1 2 [char (size 1), bool (size 1)][...] // no alignment restrictions, therefore no padding required
Comments
Post a Comment