Home  >  Article  >  Backend Development  >  Why is the size of a C struct with short members not always a multiple of the member size?

Why is the size of a C struct with short members not always a multiple of the member size?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 13:00:29527browse

Why is the size of a C struct with short members not always a multiple of the member size?

Understanding Memory Alignment in C Structs

Memory alignment is a crucial concept in C programming as it impacts the way data is stored in memory and accessed by the processor. In the context of structs, memory alignment dictates how individual members of a struct are laid out in memory.

Consider the following struct:

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

On a 32-bit machine where memory alignment is typically set to 4 bytes, one would expect the total size of this struct to be 8 bytes. However, the sizeof(myStruct) operator returns only 6 bytes.

The discrepancy arises because each member of the struct, being an unsigned short, has a size of 2 bytes. Since all members are of the same size, no padding is inserted between them. As a result, the struct occupies 6 bytes in memory.

Now, let's modify the struct:

<code class="c">typedef struct {
    unsigned short v1;
    unsigned short v2;
    unsigned short v3;
    int i;
} myStruct;</code>

In this case, the presence of an int member, which has a size of 4 bytes, changes the memory alignment of the struct. The int member must be aligned on a 4-byte boundary. Since it is preceded by 6 bytes, 2 bytes of padding are inserted between v3 and i. This brings the total size of the struct to 12 bytes, as confirmed by sizeof(myStruct).

In summary, memory alignment in C structs ensures that members are properly aligned in memory to optimize processor performance and reduce memory usage. Types are only aligned to a boundary as large as the type itself. When a larger type is introduced, it sets the alignment for the entire struct, potentially introducing padding to maintain the desired alignment.

The above is the detailed content of Why is the size of a C struct with short members not always a multiple of the member size?. 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