Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Welcome Guest | Log In | Register | Benefits
Channels ▼
RSS

C/C++

Padding and Rearranging Structure Members



Related Reading


More Insights




rsjethani

Excellent article man...just one question though...how can
I find the alignment requirements of my processor...does the OS has a say in this?thanks.

mwb1100

@Emani:

There's no undefined behavior there. The `#pragma pack` directive tells the compiler to pack the struct so there's no padding (note that all of this is beyond what's required by the standard); since the compiler knows that the offset of `m2` member is (or might be) unaligned, the compiler will generate code that accesses the member in such a way the there is no unaligned access. For example, the compiler may use a series of shifts and byte accesses.

However, the following *would* likely result in undefined behavior:

    int* p = &var.m2;

*p = 42;

The compiler should generate at least a warning when assigning the address of an unaligned int member to a plain-old int pointer.

Emani

"a program that attempts to access an improperly aligned object produces undefined behavior. This means that the program is in error, but the exact consequences of that error are platform-dependent". Having said this

I would like to know the behavior of following code on a platform which doesn't support improper aligned object access

#pragma pack(push, 1)
typedef struct widget widget;
struct widget
{
char m1;
int m2;
char m3;
};

widget var;
var.m2 = 20; --> accessing int

Drengeland

forget my previous silly question. Each member has to be aligned, so its not sufficient that sizeof is a multiple of 4 (than 8 would be enough)

Drengeland

I do not understand why 6 bytes have to added as trailing padding to the widget structure. 2 more bytes should be sufficient?