I am trying to understand why alignment matters when dealing with data structures and why would it affect memory access performance. I stumbled upon a C syntax, __attribute__((packed)); which what I understand, signals the compiler to not pad extra bits for alignment.
Say:
struct sampleStruct{
uint8_t foo;
uint8_t anotherFoo;
};
foo and anotherFoo equals to 16-bits but add an extra 16-bits to align with the natural word size of 32-bits processors.
Okay let's add another data structure:
struct anotherStruct{
uint8_t fooZero;
uint8_t fooOne;
}__attribute__((packed));
struct sampleStruct{
uint8_t foo;
uint8_t anotherFoo;
};
My question is, when initializing a packed data structure does it affect how other data structures are aligned in memory?
- Maybe the compiler re-orders how these data structure are created? (sampleStruct then anotherStruct)
- How about when there are two programs running on a system with the first program having an unaligned
structwhile the second program has an alignedstruct? Would it leave a "gap" in memory or would the otherstructbe unaligned?
Sorry for the dumb question. This has been boggling my mind for quite some time. I want to know how memory alignment works and how it affects the processor in accessing memory.
Generally speaking, a variable that takes up n bytes can be read / written more effectively from memory if it resides at an address divisible by n. On some processors (notably, not x86) attempting to read / write in an unaligned manner can cause a hardware trap.
So while packing a structure can reduce its size, it typically means slower memory access (if access can happen at all).
Packing a structure doesn't affect other structures or other types in general. Each different type, whether it be a "base" type or a derived type, has its own alignment, so a variable of a given type is placed based on that type's alignment and where there may be available space. The alignment of variables of some other type won't have a direct effect on that.
As for other processes, they are completely independent of each other so there's no reason that the internal data structures of one would have any affect on the internal data structures of another.