MEMS MEMS - 1 month ago 17
C++ Question

Memory padding issues using __declspec

based on MSDN the __declspec(align(x)) should add x bit padding after the member variables for example:

#include <iostream>
using namespace std;
void main()
{
struct test
{
__declspec(align(32))char x;
__declspec(align(32))int i;
__declspec(align(32)) char j;
};
cout << sizeof(test) << endl;//will print 96 which is correct
}


now consider the following case:

#include <iostream>
using namespace std;
void main()
{
struct test
{
char x;
int i;
char j;
};
cout << sizeof(test) << endl;//will print 12
//1 byte for x + 3 bytes padding + 4 bytes for i + 1 byte for j +3 bytes padding =12
}


but if i change the code to this:

#include <iostream>
using namespace std;
void main()
{
struct test
{
char x;
int i;
__declspec(align(1)) char j;
};
cout << sizeof(test) << endl;//will print 12 again!!!!

}


why it is giving me 12 instead of 9! i am telling the compile that i don't want any padding after j.

Answer

__declspec(align(1)) char j doesn't do anything - a char requires no special alignment with or without the __declspec.

Imagine you later declare an array of test: test arr[2];. Here, both arr[0].i and arr[1].i must be aligned on the 4-byte boundary; that requires that sizeof(arr[0]) be a multiple of 4. That's why there's padding at the end of the structure.