fbpx

What is byte alignment or memory alignment in C and C++ ?

(Last Updated On: May 15, 2010)

What is byte alignment or memory alignment in C and C++ ?
When measuring the total size of derived class, you must include the base class members as well. You need to include potential byte alignment as well.
Byte alignment is when a library may return a size of unused bytes but instead manages to shift your data around using more byte than you expect. Compilers might be designed not meet certain older 16/32 byte processors. This seems to happen a lot in structures. For instance:
The compiler padding is illustrated in the following example. Here a char is assumed to be one byte, a short is two bytes and a long is four bytes.
User Defined Structure

struct Message
{
short opcode;
char subfield;
long message_length;
char version;
short destination_processor;
};

Actual Structure Definition Used By the Compiler

struct Message
{
short opcode;
char subfield;
char pad1; // Pad to start the long word at a 4 byte boundary
long message_length;
char version;
char pad2; // Pad to start a short at a 2 byte boundary
short destination_processor;
char pad3[4]; // Pad to align the complete structure to a 16 byte boundary
};
In the above example, the compiler has added pad bytes to enforce byte alignment rules of the target processor. If the above message structure was used in a different compiler/microprocessor combination, the pads inserted by that compiler might be different. Thus two applications using the same structure definition header file might be incompatible with each other.
Thus it is a good practice to insert pad bytes explicitly in all C-structures that are shared in a interface between machines differing in either the compiler and/or microprocessor.

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!
Don't miss out!
Get my TRADE LIKE A BOSS 2 PDF Books

You will received instantly the download links.

Invalid email address
Give it a try. You can unsubscribe at any time.

NOTE!

Check NEW site on stock forex and ETF analysis and automation

Scroll to Top