0

How structs in C are saved in the memory?

Why sometimes the struct length in the memory is bigger than expected?

Meny
  • 23
  • 1
  • 3

2 Answers2

2

That's called data structure alignment.

Although not a perfect duplicate, you can find a good explanation of this in C at Structure padding and packing

Community
  • 1
  • 1
nvoigt
  • 75,013
  • 26
  • 93
  • 142
0
  • Structs are stored as a concatenation of the variables they are declared to contain.
  • The variables are stored in the order they are declared. The address of the beginning of the struct is the address of the beginning of the first variable it contains.
  • There may be a gap between the rest of the variables in the struct memory layout (or even at the end of the struct). This is done to align the variables to memory addresses from which they can be fetched.
    • Some architectures can only fetch aligned data.
    • Most architectures that can fetch unaligned data, suffer a performance penalty when doing so.
Theodoros Chatzigiannakis
  • 28,773
  • 8
  • 68
  • 104