Pragma Pack ( push , 1) (day 36)

How do you know what kind of alignment will performed to the start of that structure?

Edited by Livet Ersomen Strøm on
Kladdehelvete
How do you know what kind of alignment will performed to the start of that structure?

If my memory doesn't fail me, that should tell msvc to pack the members at one byte granularity, meaning that if you have (for instance)
1
2
3
4
5
6
struct foo
{
   char a;
   int b;
   short c;
};

the sizeof() would be 1+4+2 instead of 4+4+4 for dword packing.

Historically I remember seeing the pragma pack() being used to "easily" load binary files off disk, but that's a rather fragile thing portability-wise (especialy if we get to small/big endianess things). The only other reason I can think of is if you want to save memory if you're allocating truly enormous amount of those structures. Or maybe for cache optimization, but that would go into the "premature optimization" bin in this case.

Apart from those, it's better to leave the packing alone and let the compiler generate stuff that's fast to access.
sol_hsa

If my memory doesn't fail me, that should tell msvc to pack the members at one byte granularity, meaning that if you have (for instance)
1
2
3
4
5
6
struct foo
{
   char a;
   int b;
   short c;
};

the sizeof() would be 1+4+2 instead of 4+4+4 for dword packing.


I understand that the Size will differ. But how will a pointer look like if I declear it as a static variable, or an array?

if the previous variable in the source ended at address... 010
would I get a pointer to 011 for my variable?
Kladdehelvete
I understand that the Size will differ. But how will a pointer look like if I declear it as a static variable, or an array?

if the previous variable in the source ended at address... 010
would I get a pointer to 011 for my variable?


That's easy enough to experiment..

Without pragma pack:
1
2
3
4
5
6
7
sizeof() = 12
.a ofs 0x00
.b ofs 0x04
.c ofs 0x08
.a ofs 0x0c
.b ofs 0x10
.c ofs 0x14


With pragma pack:
1
2
3
4
5
6
7
sizeof() = 7
.a ofs 0x00
.b ofs 0x01
.c ofs 0x05
.a ofs 0x07 
.b ofs 0x08
.c ofs 0x0c
You can actually inspect a structure's layout in VisualStudio with the hidden switches
1
/d1reportSingleClassLayout<name> and /d1reportAllClassLayout

They print the layout of one or all structs to with the output of the compiler.
For example the struct foo with default alignment:
1
2
3
4
5
6
7
8
1>  class foo	size(12):
1>  	+---
1>   0	| a
1>    	| <alignment member> (size=3)
1>   4	| b
1>   8	| c
1>    	| <alignment member> (size=2)
1>  	+---
bqq
You can actually inspect a structure's layout in VisualStudio with the hidden switches
1
/d1reportSingleClassLayout<name> and /d1reportAllClassLayout



Neat! Luckily you generally don't need to, though =)