Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable structure padding in C without using pragma

Tags:

c

pragma

How can I disable structure padding in C without using pragma?

like image 730
Manu Avatar asked Nov 29 '10 07:11

Manu


2 Answers

There is no standard way of doing this. The standard states that padding may be done at the discretion of the implementation. From C99 6.7.2.1 Structure and union specifiers, paragraph 12:

Each non-bit-field member of a structure or union object is aligned in an implementation-defined manner appropriate to its type.

Having said that, there's a couple of things you can try.


The first you've already discounted, using #pragma to try and convince the compiler not to pack. In any case, this is not portable. Nor are any other implementation-specific ways but you should check into them as it may be necessary to do it if you really need this capability.


The second is to order your fields in largest to smallest order such as all the long long types followed by the long ones, then all the int, short and finally char types. This will usually work since it's most often the larger types that have the more stringent alignment requirements. Again, not portable.


Thirdly, you can define your types as char arrays and cast the addresses to ensure there's no padding. But keep in mind that some architectures will slow down if the variables aren't aligned properly and still others will fail miserably (such as raising a BUS error and terminating your process, for example).

That last one bears some further explanation. Say you have a structure with the fields in the following order:

char C; // one byte
int  I; // two bytes
long L; // four bytes

With padding, you may end up with the following bytes:

CxxxIIxxLLLL

where x is the padding.

However, if you define your structure as:

typedef struct { char c[7]; } myType;
myType n;

you get:

CCCCCCC

You can then do something like:

int *pInt = &(n.c[1]);
int *pLng = &(n.c[3]);
int myInt = *pInt;
int myLong = *pLng;

to give you:

CIILLLL

Again, unfortunately, not portable.


All these "solutions" rely on you having intimate knowledge of your compiler and the underlying data types.

like image 100
paxdiablo Avatar answered Oct 07 '22 08:10

paxdiablo


Other than compiler options like pragma pack, you cannot, padding is in the C Standard.

You can always attempt to reduce padding by declaring the smallest types last in the structure as in:

struct _foo {
     int a;  /* No padding between a & b */
     short b;
} foo;

struct _bar {
     short b; /* 2 bytes of padding between a & b */
     int a;
} bar;

Note for implementations which have 4 byte boundaries

like image 29
SiegeX Avatar answered Oct 07 '22 09:10

SiegeX