What is data structure padding in c++ and how do i check the number of bytes padded bytes?
class a { public: int x; int y; int z; };
padding is done for performance reasons - see this article Data Structure Alignment for more info.
To see whether the compiler pads your data structure you could write a simple program:
#include <iostream>
class a {
public:
int x;
int y;
int z;
};
int main()
{
std::cout << sizeof(a) << std::endl; // print the total size in bytes required per class instance
a anInstance;
std::cout << &anInstance.x << std::endl; // print the address of the x member
std::cout << &anInstance.y << std::endl; // as above but for y
std::cout << &anInstance.z << std::endl; // etc
}
I added the public declaration to avoid compiler errors - It will not affect the size or padding.
Edit: Running this on my macbook air gives the following output: 12 0x7fff5fbff650 0x7fff5fbff654 0x7fff5fbff658
This shows that on my machine the total size is 12 bytes, and each member is 4 bytes apart. The ints are 4 bytes each (which can be confirmed with sizeof(int)). There is no padding.
Try this with different members in your class, for example:
class b {
public:
char w;
char x[6];
int y;
long long z;
};
Processors require that certain types of data have particular alignments. For example, a processor might require that an int
be on a 4-byte boundary. So, for example, an int
could start at memory location 0x4000
but it could not start at 0x4001
. So if you defined a class:
class a
{
public:
char c;
int i;
};
the compiler would have to insert padding between c
and i
so that i
could start on a 4-byte boundary.
struct A
{
char c;
int i;
};
int main(int argc, char *argv[])
{
A a;
cout << "sizeof struct = " << sizeof(A) << endl;
cout << "sizeof items = " << sizeof(a.c) + sizeof(a.i) << endl;
return 0;
}
Lol just create 2 identical structs, make one of them packed e.g.
struct foo {
int a;
char b;
int c;
}
struct bar {
int a;
char b;
int c;
} __attribute__((__packed__));
sizeof(foo) - sizeof(bar)
will give you the amount of padding. Or you could also calculate manually like Duck suggested.