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?
As the name implies, they're trying to force Mtx
es 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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With