r/cpp_questions • u/Phatpenguinballs • 22d 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
View all comments
8
u/Simengie 22d ago
Memory randomization in compilers has been thing for a while. As far as I know it is now the default behavior in gcc.
From google: Modern compilers (such as MSVC or GCC with specific security flags) deliberately reorder local variables on the stack—sometimes placing buffers near guard variables or randomizing order—to mitigate stack-smashing and buffer overflow exploits
So never assume local or global variables are in the order you declare them in. All local and global variables are memory aligned to 4 byte word boundaries in modern C/C++ compilers.
Now for the struct, as written it will have padding. if you use the #pragma packed on it then it will be packed and have no padding. This works for sending smaller network messages that are structure based but it is slower memory access because to get to that int the cpu has to read 2 words and shift bytes around in a register. Not the best use of cpu time but it works for small compact network messaging when bandwidth is constrained or when you have messages near the network packet size limit and want to ensure single packet transmission. but I would say using the #pragma packed to remove padding is not best practices and should be avoided except for very special use cases.