Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ struct containing unsigned char and int bug

Tags:

c++

struct

byte

Ok i have a struct in my C++ program that is like this:

struct thestruct
{
 unsigned char var1;
 unsigned char var2;
 unsigned char var3[2];
 unsigned char var4;
 unsigned char var5[8];
 int var6;
 unsigned char var7[4];
};

When i use this struct, 3 random bytes get added before the "var6", if i delete "var5" it's still before "var6" so i know it's always before the "var6".

But if i remove the "var6" then the 3 extra bytes are gone.

If i only use a struct with a int in it, there is no extra bytes.

So there seem to be a conflict between the unsigned char and the int, how can i fix that?

like image 311
powerfear Avatar asked May 30 '10 04:05

powerfear


1 Answers

The compiler is probably using its default alignment option, where members of size x are aligned on a memory boundary evenly divisible by x.

Depending on your compiler, you can affect this behaviour using a #pragma directive, for example:

#pragma pack(1)

will turn off the default alignment in Visual C++:

Specifies the value, in bytes, to be used for packing. The default value for n is 8. Valid values are 1, 2, 4, 8, and 16. The alignment of a member will be on a boundary that is either a multiple of n or a multiple of the size of the member, whichever is smaller.

Note that for low-level CPU performance reasons, it is usually best to try to align your data members so that they fall on an aligned boundary. Some CPU architectures require alignment, while others (such as Intel x86) tolerate misalignment with a decrease in performance (sometimes quite significantly).

like image 119
Greg Hewgill Avatar answered Sep 29 '22 11:09

Greg Hewgill