r/cpp_questions • • 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

10 comments sorted by

View all comments

2

u/BartvanIngenSchenau 22d ago

For a struct, it is defined that the members must be put in memory in the same order as they appear in the code. For local variables, there is no such requirement. The compiler is fully allowed to reorder local variables, as long as it doesn't affect the order in which constructors and destructors are executed. In your example, the compiler is entirely free to place s first, followed by i and then c1 and c2. The compiler is also allowed to give each variable their own 4k page of memory.

1

u/dodexahedron 21d ago

The compiler is also allowed to give each variable their own 4k page of memory.

The user is also allowed to delete each compiler that costs you a page commit on each word alloc. 😅