Home > Programming > Memory Alignment or Data Alignment

Memory Alignment or Data Alignment


What is Memory Alignment or Data Alignment?

Data alignment refers to where data is located in memory. All data is at least 1-byte aligned, meaning that it starts at any one byte in memory. Data that is n-byte aligned is located somewhere with a memory address that is an exact multiple of n bytes.

To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding. In a typical 32-bit machines, in one memory attempt, 4 bytes can be either read or written.

Why memory Alignment?
Performance only, Because memory can only be accessed based on particular boundaries. Trying to read data from an unaligned memory address can result in two reads from main memory and present it to the user.

Data structure alignment?
Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: 1.Data alignment and 2. Data structure padding. When a program reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system).

For example, when the computer’s word size is 4 bytes (a byte meaning 8 bits), the data to be read should be at a memory offset which is some multiple of 4. When this is not the case, e.g. the data starts at the 14th byte instead of the 16th byte, then the computer has to read two 4-byte chunks and do some calculation before the requested data has been read, or it may generate an alignment fault.

Example
int A;
int B
char c;

sizeof(A) -> 4
sizeof(B) -> 4
sizeof(c) -> 1

Hence, the total size is 9

Citation -1 : Memory Alignment

Consider the struct A
struct A{
char cData1;
char cData2;
int nValue1;
}A;

Sizeof(A) -> 8

struct B{
char cData1;
int nValue1;
char cData2;
}B;

Sizeof(B) -> 12

Advertisements
Categories: Programming
  1. No comments yet.
  1. No trackbacks yet.

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: