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?
b
with precisely 0 or 1 I doubt this is really worth it. There's better ways of trying to detect memory overwrites that don't require programmers to add code to every single check they perform – Excogitateint
? Wouldn't they be just as critical, or even more so? – Easelelse if
withelse
, as well as terminating allswitch
withdefault
. – Gluckstdbool.h
here instead, an optimizing compiler would simply optimize away the third path in this case, and this would likely happen with other "impossible" checks you try to implement. – Caryopsisb
is declared as a_Bool
. The C standard does not say what happens if, when reading a_Bool
object, the bits in memory are other than those used for the values 0 or 1. To detect invalid bit patterns, you should examine the contents of memory using a pointer tounsigned char
. Ifb
is some integer type other than_Bool
, then that code might work (although the C standard still permits padding bits and trap representations). – Senatebool
(_Bool
) type was standardized and widely used, regular integers were used as booleans. Every time I have to work in one of those I hate it. What is the type ofb
? If it is abool
or_Bool
, you're not going to get far trying to do what you're doing. You get into some weird behavior pretty quickly. This example: godbolt.org/z/Chcd7M returns the value56
from a function returningbool
. – Balefireb
in your example code has type_Bool
(orbool
), it would be interesting to see which of your three branches is taken if it has a value other than 0 or 1. The behavior is probably undefined. So if you really need to check for things like this, it is probably better to avoid using_Bool
(orbool
) as the type of such objects altogether. – Staminody