Can variables adjacent to a bit field be corrupted?

I ran into a problem very similar to the one described by the Linux Kernel community - Betrayed by a bit field

The heart of the problem is that GCC issues 64-bit reads to access 1-bit bit fields. This causes an unexpected side effect of reading in adjacent fields, which can be changed elsewhere in the program. When the value of the changed bit field is written back, the adjacent variable old value is also written back, thereby losing any modification made to it by other threads.

My problem is slightly different. I have a class / structure like this -

class Group {

    uint8 adjVariable;
    volatile bool  flag1: 1;
    volatile bool  flag2: 1;
    // so on...
    volatile bool  flag10: 1;
};

Access to these variables -

Group::fun() {
    Group_Scoped_lock();
    // adjVariable was 12 here.
    if ( adjVariable > 0 ) {
        adjVariable = 0; // <------- EXPLICIT ZERO ASSIGNMENT
    }
    // some code that doesn't affect adjVariable 
    bool1 = false;
    bool2 = false;
    bool3 = false;
    assert( adjVariable == 0 ); // <---- This assert is tripping stating that adjVariable is 12!!
}

"" GCC, , adjVariable Group_lock() . , , .

, 64- - , adjVariable ZERO adjVariable , 12 adjVariable? ? assert? , ?

, , , adjVariable, , - . ?

g++, ++ 98 Fedora 12. , , 6

+4
1

adjVariable , 0 .

bool - , adjVariable - , , , .

64- , , 8 (, 7- adjVariable flag1). , 64- .

++ 11 , - ++ 98: adjVariable assert adjVariable.

+1

Source: https://habr.com/ru/post/1681051/


All Articles