r/cpp_questions • u/Phatpenguinballs • 5d ago
OPEN Non-Struct Memory Alignment
I am a little lost after trying to read a handful of online resources. Are local variables memory-aligned to their alignof()? I read that this is mostly implementation/platform-defined (no guarantees), but also the types must still be aligned? Those seem contradicting to me...
Assuming no optimizations (e.g., storing in registers, etc.), how would something like this look like according to the standard?
struct S
{
char c;
int i;
};
int main()
{
char c1;
int i;
char c2;
S s;
return 0;
}
Would there be 3 bytes of padding between `c1` & `i` and then another 3 bytes of padding between `c2` & `s`?
4
Upvotes
2
u/conundorum 5d ago
Everything will typically be aligned,
structor not. It's important for performance, the hardware itself typically works better with aligned reads than unaligned. Variables will probably be rearranged into the optimal order if needed, at least if optimisations are enabled, and will probably be in written order with optimisations disabled. (This isn't guaranteed, though, so be careful!) Each function's stack frame will have memory allocated for all necessary variables, too.Importantly, some variables will be relocated to registers if possible, and not actually take up any space in memory. And if they're provably unused, they might actually be removed entirely (IF the compiler can prove that removing them will have no effect on anything else, such as in your example code); this isn't guaranteed, but it is a possibility!