Memory Padding

The default behavior is the compiler will add some padding to your data structure to improve the efficient of the CPU reading.

Example

Consider this program below:

#include <iostream>

int main() {
    struct MyStruct {
        char a; // 1 byte
        int b; // 4 bytes
        char c; // 1 byte
    };

    std::cout << "struct size: " << sizeof(MyStruct) << std::endl;

    return 0;
}

One would think that the value of MyStruct would be 6 bytes. However it's 12 bytes:

❯ make
struct size: 12

This is because how the compiler assign the memory to the program.

By default, the compiler will try to store the memory in the size of the maximum alignment,

For example, if the child has just char, the alignment is 1 since char is only 1. i.e

struct MyStruct {
    char a; // 1 byte
    char b; // 1 bytes
    char c; // 1 byte
};

sizeof(MyStruct) // 3 bytes

If the child has a mix of char, and int, the alignment becomes 4 since int is 4 is the largest alignment.

Similarly, if we have a long it will be 8.

Consider the above stack, the following will happen:

Loading...
Loading...
Loading...

Ignore padding

We can ignore the padding as well

#include <iostream>

int main() {
    struct __attribute__((packed)) MyStruct {
        char a; // 1 byte
        int b; // 4 bytes
        char c; // 1 byte
    };

    std::cout << "struct size: " << sizeof(MyStruct) << std::endl;

    return 0;
}
❯ make
struct size: 6

This is useful when the size of the object is important corresponding to byte (i.e Implementing TCP (Transmission Control Protocol) header)