Search code examples
c++memorybit-fields

Memory model in C++: Why are the two integers in struct allocated in the same memory location?


Referring to the code snippet at cppreference.com which I'm pasting below why are the integers b and c allocated in the same memory location:

struct S {
    char a;     // memory location #1
    int b : 5;  // memory location #2
    int c : 11, // memory location #2 (continued)
          : 0,
        d : 8;  // memory location #3
    struct {
        int ee : 8; // memory location #4
    } e;
} obj; // The object 'obj' consists of 4 separate memory locations

My understanding is, for example, in a system that is 1 byte = 8 bits, variable a would take 1 byte. Then b would take say 4 bytes. If both b and c goes in the same memory location which would fill 8 bytes, does that mean 8 char variables could be allocated in the same memory location in a continued fashion?

Also, how would the program know where to access b or c if they have the same memory location?


Solution

  • You missed the :5 and the :11.
    Make sure you know what they do. It is the syntax to create bitfields. (Thanks Nate for reminding the tired me of the term and for providing the useful link https://en.cppreference.com/w/cpp/language/bit_field ) Basically they say "only 5 and 11 bits needed, feel free to squeeze them into one int".
    This assumes what is quite likely, that int is at least 16bit (to squeeze the two) or at least 24bit (to squeeze the third in) in your environment.

    When you say "same memory location", it is kind of correct, they are in the same (probably) 32bit location, but not exactly in the same memory. They are in different bits. So the system accesses them in some way (hardware depending and not defined) which only uses part of the bits. You may think of it as the compiler/CPU doing some bit shifting and masking, but just as a model of what happens.