C++ struct packing memory consumption

AC 1 Reputation point

The following code prints 12 (bytes):

struct examplestruct {  
    unsigned char varb;  
    unsigned int varc;  
    unsigned char vacd;  
    unsigned char vare;  
int main() {  
    std::cout << sizeof(examplestruct) << std::endl;  

However, if I put the unsigned int variable, varc, first, it prints 8. I was a bit surprised to see that the ordering of the struct's member variables affects memory consumption. What is the most efficient way (for memory consumption) to arrange variable types in a struct? Or is there a way for the compiler to not necessarily follow the struct's specified layout, but instead reorder the member variables in whatever way reduces memory consumption the most? I figure that there's probably a compiler flag to do this.

A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
2,625 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Barry Schwarz 666 Reputation points

    On your system, an int requires alignment on a 4-byte boundary. To insure that this requirement is met, the compiler will align the struct on a 4-byte boundary. Since it is possible to create an array of struct and each element of the array must start exactly sizeof(struct) bytes beyond the previous element, the struct must occupy a multiple of 4 bytes.

    In your first example:

    • varb will be at offset 0 from the start of the struct
    • varc will be at offset 4
    • vard at offset 8
    • vare at offset 9

    12 is obviously the smallest multiple of 4 the 10 bytes occupied by the members of lthe struct.

    In your second example, varc is at offset 0 and the remaining members are at offsets 4, 5, and 6. 8 is obviously the smallest multiple ....

    The most compact way to organize an array is to specify the members in decreasing order of alignment.

    No, the compiler cannot reorder the members. The standard requires the members to appear in the struct in the order they are specified.

    No comments