+ 1
Structure padding memory allocation
Hello Please refer below code... Is my understanding of memory layout for class variable is correct or not, specially about last member ? https://code.sololearn.com/c5T8IhEzYGKj/?ref=app
5 Antworten
+ 3
First of all, you can use this 'equation' to get the offset of a struct/class variable:
cout << (char*)&object.var - (char*)&object;
So to get the offset of 'b' you would do:
Test object;
cout << (char*)&object.b - (char*)&object;
and you'll get the output '48'. ( if you change Test to a struct or put the variables in public scope )
Then, you can use the alignof operator to check the alignment requirement of a type. ( not to be confused with sizeof )
https://en.cppreference.com/w/cpp/language/alignof
For an int this is 4, double 8, float 4, char 1
Then I believe the alignment of the class itself is the alignment of the biggest alignment type in the class ( in this case 8 )
That means that your Test structure looks like
'a' at an offset of 0
'arr' at an offset of 4
then 4 bytes of padding at an offset of 44 ( because b has an alignment of 8 and the next multiple of 8 is at 48 )
'b' at an offset of 48
'c' at an offset of 56
'd' at an offset of 60
then another 3 bytes of padding at an offset of 61 ( to match the class alignment )
( and 'x' being ignored here because of the static )
In this case you can change arr[10] to arr[11] and still get the same class size.
But if you do that change and move 'd' before 'b' you'll get a bigger class size because of more wasted padding.
Just trying to say that you should pay attention to the order you place the variables.
+ 1
int a; // 4 bytes
int arr[10]; // 40 bytes
static int x; // no class object memory
double b; // 8 bytes
float c; // 4 bytes
char d; // 1 byte but consumes 4
Modified: Consumption of 4 extra bytes is not known to me because if you comment that line with 'double' and execute, you will get 52. May be someone better at it could explain.
+ 1
I guess 12 is not for double...it's 8 only and it gets started at location in multiple of 8 as 8 is max size out of all elements size in the class.
+ 1
Ketan Lalcheta yes it seems correct.
So it will pad to the multiple of the largest individual element size in the class.
Isn't it?