Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does aligning structures help in C?

Tags:

c

structure

I came across this C code and I'm trying to understand it:

typedef long    Mtx_t[4][4];

typedef union {
    Mtx_t m;
    long long int   force_structure_alignment;
} Mtx;

The first typedef defines Mtx_t as a 4x4 matrix, that much I understand. But the second typedef for Mtx just calls for the previous type and adds a long long int called force_structure_alignment.

What is the purpose of this? Why not just define Mtx as the 4x4 matrix and be done with it?

like image 971
user3360203 Avatar asked Jun 08 '16 22:06

user3360203


3 Answers

As the name implies, they're trying to force Mtxes to be placed in memory with the address alignment requirements of a long long, rather than a long. This may be important for requirements imposed by the OS or the processor architecture. Google suggests that "Mtx" is probably short for "mutex", and a C mutex implementation would be dealing with some pretty low-level interfaces.

like image 119
user2357112 supports Monica Avatar answered Nov 04 '22 11:11

user2357112 supports Monica


It can be done for efficiency with the processor architecture. For example, if the size of Mtx_t is an odd number of bytes and the hardware's instruction set/memory architecture imposes a cost when accessing an odd address, you'll want to make sure all your Mtx_t records will sit along addresses which are cheaper to access.

There also might be some need to work with a fixed size block of memory such as with coprocessors. Using a padded structure can make that easier to manage.

Read more about it here: https://en.wikipedia.org/wiki/Data_structure_alignment

like image 39
Jason Avatar answered Nov 04 '22 10:11

Jason


There is data bus on the chip which carries data for read/write. For faster memory access, these buses designed to carry data in multiple of bytes e.g. 4/8/16 bytes. But these bus can't read/write data from any arbitrary address with equal efficiency. For example an 8-byte data bus will be faster to read/write data from a memory which is aligned at 8-byte boundary. That's why for high efficiency, large size data/structure are recommended to be aligned such that a fast access be feasible. In your example it is done by exploiting compiler's implementation of managing structures which may not yield the desire result. But compiler can be explicitly told about the alignment of a variable by using keywords e.g. gcc uses 'aligned' keyword

like image 24
Ashwani Avatar answered Nov 04 '22 10:11

Ashwani