C boolean invalid values handling

518 Views Asked by At

I'm in a safety critical embedded C project and there's a discussion about detecting memory corruptions (e.g. buffer overflows) in boolean variables. As everyone knows, in C, the "boolean" type is actually an N-bit integer and that means it has potentially 2N-2 invalid values. E.g. if you declare FALSE as 0 and TRUE as 1 (by macros, constants or enums), then it is possible to say that <0 (in case of signed type) or >1 are consequences of memory corruption (or a bug).

So theoretically it should be possible construct such fault capture code blocks:

if (b == TRUE)       { /* Good, do something               */ }
else if (b == FALSE) { /* Good, but don't do anything      */ }
else                 { /* Memory corruption. Deal with it. */ }

Or do it with switch-case. It is mandatory to have for state variables and other enum types, but doing it for booleans certainly adds a lot of code and my question is - is it worth the effort?

1

There are 1 best solutions below

5
On

Depends on the safety class you try to reach. The above example is not very safe when considering that the memory corruption also could mean a change in bit0 which would make a TRUE to FALSE or vice versa.

Therefore I have seen much more wrapping to secure critican variables.

such as storing each variable in a struct consisting of the variable itself and its complement as copy.

struct tag_intvar{
    int variable;
    int complement;
};

and then working with getter/setter functions to grant atomic access and and perform consistensy checking/handling.

int setintvalue(tag_intvar* var, int val){
    if(isconsistent(var)){
        var.variable = val;
        var.complement = ~val;
        return TRUE;
    }
    //... inconsistent... handler
    return FALSE;
}

while

int isconsistent(tag_intvar* var){
   return (var.variable == ~var.complement)?TRUE:FALSE;
}