Microcontroller Embedded C Programming Lecture 147| Aligned and un-aligned data storage

  • Post author:
  • Post category:Blog

 

 

Aligned and un-aligned data storage

 

Aligned Data Storage: When data is stored in aligned memory, it means that the memory address at which the data starts is a multiple of the data size.

For example, if you have a 4-byte integer, it should be stored at an address that is divisible evenly by 4. Aligned data storage is generally more efficient because it allows the processor to fetch data in a single memory access, rather than requiring multiple accesses for unaligned data.

Unaligned Data Storage: Unaligned data storage means that the data is stored at memory addresses that do not match the data size. Accessing unaligned data may require multiple memory accesses, potentially impacting performance. In some architectures, unaligned memory access can also cause alignment faults or exceptions.

 

Aligned/un-aligned data access

  • For efficiency, the compiler generates instructions to store variables on their natural size boundary addresses in the memory.
  • This is also true for structures. Member elements of a structure are located on their natural size boundary. 

 

Let’s explore about natural size boundaries of different data types.

data storage
Figure 1. Natural size boundary

 

Let’s first consider the char data type.

What is the natural size of a char data type? 

It’s 1 byte. Char type variables can be placed at any addresses ending with 0, 1, 2, 3, 4, etc. So, let’s consider 0403010 0403011 0403013 0403014 0403015 are the addresses.

 

What is the natural size of a short type variable?

It’s 2 bytes. Short type variables will be stored in the memory at addresses that end with 0, 2, 4, 8, etc.

And in the same way, int type variables will be stored at addresses that end with 0, 4, 8, C, etc. 

So, the compiler does this automatically when you generate the code. Basically, when you compile the code, the compiler takes care of generating instructions that will arrange these variables in the memory in an aligned fashion. 

When you compile the code, the compiler generates the instructions to store the variables in memory according to the variables natural size boundary, and that is what we call align data storage.

In the following article, let’s write a simple program to investigate the data alignment of variables of different data types.

 

FastBit Embedded Brain Academy Courses

Click here: https://fastbitlab.com/course1

 

FastBitLab

The FastBit Embedded Brain Academy uses the power of internet to bring the online courses related to the field of embedded system programming, Real time operating system, Embedded Linux systems, etc at your finger tip with very low cost. Backed with strong experience of industry, we have produced lots of courses with the customer enrolment over 3000+ across 100+ countries.

Leave a Reply