Home  >  Article  >  Backend Development  >  Why Does `sizeof(myStruct2)` Return 12 Bytes While `sizeof(myStruct1)` Returns 6 Bytes?

Why Does `sizeof(myStruct2)` Return 12 Bytes While `sizeof(myStruct1)` Returns 6 Bytes?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 10:01:03398browse

Why Does `sizeof(myStruct2)` Return 12 Bytes While `sizeof(myStruct1)` Returns 6 Bytes?

Memory Alignment in C Structs

When dealing with structures in C, memory alignment plays a crucial role in optimizing memory usage and performance. If you're puzzled by the difference in memory alignment between the following two structs:

<code class="c">typedef struct {
    unsigned short v1;
    unsigned short v2;
    unsigned short v3;
} myStruct1;

typedef struct {
    unsigned short v1;
    unsigned short v2;
    unsigned short v3;
    int i;
} myStruct2;</code>

where both myStruct1 and myStruct2 have the same combined data size of 6 bytes, but myStruct2 reports a size of 12 bytes using sizeof(), the answer lies in memory alignment.

On most 32-bit machines, the alignment boundary is typically 4 bytes. This means that structures are aligned to the nearest multiple of 4 bytes. In myStruct1, each member is 2 bytes, so no padding is inserted between them, and the actual size remains at 6 bytes.

However, in myStruct2, the addition of a 4-byte integer (int) requires a 4-byte alignment boundary. Since the initial 6 bytes of data from the original struct do not align to a 4-byte boundary, 2 bytes of padding are inserted between v3 and i. This padding ensures that i starts on a 4-byte boundary, resulting in a total size of 12 bytes for myStruct2.

Remember, in most cases, structures are only aligned to the boundary of their largest member. In this case, the int member in myStruct2 determines the alignment boundary, which explains the difference in memory alignment between the two structs.

The above is the detailed content of Why Does `sizeof(myStruct2)` Return 12 Bytes While `sizeof(myStruct1)` Returns 6 Bytes?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn