Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid struct padding in C++

In my code, I have the following struct:

struct foo {
 int a;
 int b;
};

In b, only values between 0 and 100 are stored. So in general, I could replace it by a char. But than the size of the struct is the same due to padding effects. As my code contains vectors and sets of these structure with several million entries, it would bring the memory usage down by more than one third if I could circumvent padding in some way. Is there any possibility to do this, e.g. some other (boost) data container which behaves in the same way?

Edit: I use both, the GNU and the Intel compiler on Linux systems:

like image 536
Thomas W. Avatar asked Nov 01 '12 14:11

Thomas W.


1 Answers

Moving my comment as an answer, as the community advised :)

This is compiler dependent. What you need is to use struct packing.

For Visual Studio, you need #pragma pack and for gcc, you need to use an attribute packed.

For more information, see C++ struct alignment question

Hope that helps, sorry I can't really test it right now, but that's what you need

like image 188
Kiril Kirov Avatar answered Sep 20 '22 17:09

Kiril Kirov