Reputation: 133
Just noticed something that looks strange to me. Visual C++ doesn't align object in their required boundary by default. For example long long is aligned to 4 bytes boundary, while __alignof(T) returns 8 (as far as I see it always returns size of the type). So it looks like it is not properly aligned. For example
long long a1;
char g;
long long a2;
// alignment check for &a2 fails
if (((uintptr_t)&a2 & (__alignof(long long) - 1)) != 0) // failed
I also tried just to print the pointer, the value of &a2
is 0x0035F8FC
(3537148
in dec).
Is there something I get wrong? I need properly aligned object of type long long. What can I do about that?
I could use __declspec(align())
Microsoft extension, but it requires literal number, so I can't write anything like that.
__declspec(align(__alignof(long long))) long long object;
Upvotes: 1
Views: 2496
Reputation: 26171
VC doesn't guarantee automatic stack alignment of variables, at most the variable will be aligned to the stacks alignment(generally 4 bytes on 32 bit systems). If you need special alignment, you need to use __declspec(align(x))
, just like MSVC's SSE types(like __m128
), else you'll need to use _aligned_malloc
instead
Upvotes: 4
Reputation: 13690
The alignment should minimize the memory cycles on RAM access. The 4 byte alignment uses only two 32-bit acccesses to the long long
. The 8 byte aligment doesn't improve the behavior. The compiler has a default alignment that can be overwritten with the /Zp
option.
See also: Configuration Properties C/C++ Code Generation Struct Member Aligment.
Upvotes: 0