"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why does `sizeof(myStruct)` return 6 bytes instead of 8 bytes for a struct with three `unsigned short` members?

Why does `sizeof(myStruct)` return 6 bytes instead of 8 bytes for a struct with three `unsigned short` members?

Published on 2024-11-18
Browse:772

Why does `sizeof(myStruct)` return 6 bytes instead of 8 bytes for a struct with three `unsigned short` members?

Memory Alignment in C Structs: Understanding the Size Discrepancy

When working with C structs, memory alignment plays a crucial role in determining the actual size of the struct in memory. Memory alignment refers to the placement of data structures in memory addresses that are divisible by specific boundaries. This ensures efficient data access and performance optimization.

Consider a 32-bit machine where the memory alignment is typically set to 4 bytes. In this context, a struct composed of several unsigned short members, such as:

typedef struct {
    unsigned short v1;
    unsigned short v2;
    unsigned short v3;
} myStruct;

One would expect the memory size of this struct to be 8 bytes (3 x 2 bytes). However, the sizeof(myStruct) operator returns only 6 bytes. This discrepancy can be attributed to the alignment requirement.

In the first example, each short member occupies 2 bytes. Since the alignment boundary is 4 bytes, no padding is inserted between the members. Thus, the total size remains at 6 bytes.

In contrast, introducing an int member to the struct, as seen below, alters the alignment behavior:

typedef struct {
    unsigned short v1;
    unsigned short v2;
    unsigned short v3;
    int i;
} myStruct;

In this case, the int member requires a 4-byte alignment boundary. To ensure meeting this requirement, 2 bytes of padding are inserted between the last unsigned short member (v3) and the int member (i). This results in a total size of 12 bytes (6 bytes of data in shorts, 2 bytes of padding, and 4 bytes of data in int).

Therefore, the difference in memory size between the two structs arises from the alignment requirements of their member types. In the first struct, the alignment boundary is met by the short members themselves, while in the second struct, additional padding is required to meet the alignment boundary of the int member.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3