Skip navigation

Follow this link for a great article on byte alignment.

The deal is the VC++ compiler will sometimes pad your data structures automatically so that different variables start on word boundaries.

In VC++, you can bypass the automatic compiler padding. An example follows.

#include <iostream>
using namespace std;

// In this example, the C++ compiler will actually pad
// the PaddedStruct structure definition with unnamed variables
// so that shorts start on word boundaries.
// So between c and d, an extra, unnamed 1 byte variable
// of type char will be added in automatically by the compiler.
// This is done so that application performance is better,
// but sometimes, you don't want that.

// To get your structures to be laid out in memory
// exactly as you'd like, with no padding, you have to change
// compiler behaviour with some #pragmas.  This example shows how.


// Here is an example of a struct that gets AUTOMATICALLY
// padded out with an extra byte.
struct PaddedStruct
	char a;
	char b;
	char c;

 /* char PADDING; */ // the COMPILER will add in an extra byte here
                     // so the short gets started on a 2-byte boundary
	short d;

// Here is how you force the compiler to NOT add that extra PADDING char:
// Use the #pragma pack preprocessor directive to alter VC++ compiler behavior!
#pragma pack(push)  /* push current alignment to stack */
#pragma pack(1)     /* set alignment to 1 byte boundary */
struct UNPaddedStruct
	char a;
	char b;
	char c;
	short d;
#pragma pack(pop)   /* revert to default compiler behavior */

int main()
    cout << "sizeof(paddedStruct) " << sizeof(PaddedStruct) << endl;	    // should be 5, but its actually 6

    cout << "sizeof(UNpaddedStruct) " << sizeof(UNPaddedStruct) << endl;	// WILL be 5, b/c of #pragma
    return 0;

One Comment

  1. Addendum: Apparently you can find more about this in PshPack1.h.

    Should be in your C:\Program Files\Microsoft SDKs\Windows\v6.1\Include directory

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: