C++ struct packing memory consumption

AC 1 Reputation point
2022-12-24T00:58:39.707+00:00

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.

Developer technologies C++
{count} votes

2 answers

Sort by: Most helpful
  1. Barry Schwarz 3,746 Reputation points
    2022-12-24T04:16:39.9+00:00

    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.

    0 comments No comments

  2. Minxin Yu 13,501 Reputation points Microsoft External Staff
    2023-02-27T07:52:17.6166667+00:00

    You could refer to the document:
    Compiler handling of data alignment
    From your example, it would be

    struct examplestruct {  
        unsigned char varb;  
        char _pad0[3];
        unsigned int varc;  
        unsigned char vacd;  
        unsigned char vare;  
        char _pad1[1];
    };  
    

    And

    struct examplestruct {  
        unsigned int varc;  
        unsigned char varb; 
        unsigned char vacd;  
        unsigned char vare;  
        char _pad0[1];
    
    }; 
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.