Skip to content

Memory Alignment – Data Structure Padding

March 18, 2014

During data structure declaration, usually compiler will insert a dummy variable between structure element to enable a proper memory alignment in the data structure.

For example when declaring below structure in x86(32bit 4byte alignment), the total structure size is 12bytes(0xBFFFF68C~0xBFFFF697), with the memory address shown end of variable declaration.

typedef struct
{
    unsigned char var1;//Address:0xBFFFF68C
    int           var2;//Address:0xBFFFF690
    unsigned char var3;//Address:0xBFFFF694
}Sample;

If above structure is rearrange as below, the total use bytes will reduce to 8 (0xBFFFF68C ~ 0xBFFFF693) instead.

typedef struct
{
    unsigned char var1;//Address:0xBFFFF68C
    unsigned char var3;//Address:0xBFFFF69D
    int           var2;//Address:0xBFFFF690
}Sample;

Even though above example is shown on x86 system, it will still applies into standard MCU (specifically on 32-bit architecture)

There is two advantages of above arrangement. The first is reduction of RAM usage as shown below. Second advantage is when structure is use to read/write on non-volatile memory, a smaller data structure size would imply smaller non-volatile memory is require.

Further studies on memory alignment is here.

Advertisements

From → Embedded System

Leave a Comment

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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: