1

With C/C++ structs, normally, the final struct's size is the plain sum of the sizes of all its elements, but there are cases which this is not true.

I am looking at the technical answer (it has to be one) of why the following struct's size is not equal to the size of all its members:

#include <iostream>

struct {
    int a;
    long b;
    char c;
} typedef MyStruct;

int main() {
    MyStruct sss;
    std::cout << "Size of int: " << sizeof(int) << std::endl << "Size of long: " << sizeof(long) << std::endl << "Size of char: " << sizeof(char) << std::endl;
    std::cout << "Size of MyStruct: " << sizeof(sss) << std::endl;
    return 0;
}

Thas has the following output:

Size of int: 4
Size of long: 8
Size of char: 1
Size of MyStruct: 24

So it can be seen than the size of MyStruct is not 4+8+1 (13) rather, it is actually 24, but why?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
StormByte
  • 1,266
  • 1
  • 13
  • 33

1 Answers1

2

Because C allows compilers to add padding between the elements of a struct to make the generated code more performant.

Some hardware allows accessing multi-byte data faster when such data is placed at memory addresses divisible by the size of the data. For example, accessing a 32-bit int may go significantly faster when the int is located at address 0x8004 or 0x8008 than when the same int is located at an address 0x8003 or 0x8006. The standard allows compilers to adjust offsets of struct members to make use of such optimization.

Moreover, there are platforms where accessing a multi-byte value not aligned with the memory space results in an error: for example, reading a 16-bit int from an odd address in 68000 architecture triggers bus error. Compilers know this, and they add unused space to your struct so that accessing multi-byte fields does not trigger an error.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • *Or* simply to conform with the underlying architecture (many processors don't accept unaligned memory accesses, depending on the size of the access). – syam Sep 24 '13 at 20:49