Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gcc: how to detect bad `bool` usage

Is there some way to detect the bad usage of bool values in code like

#include <stdbool.h>

void *foo(void)
{
    return false;
}

int bar(void)
{
    return true;
}

Both functions are accepted by gcc (8.3.1) and clang (7.0.1) without any warnings

$ gcc -Wall -W -pedantic -c x.c
$ clang -Xclang -analyzer-checker=alpha --analyze  -Wall -W -pedantic -c x.c
$ clang -Wall -W -pedantic -c x.c
$

Compiling as C++ code would detect the problem in foo() but is not an option but rest of code is C, not C++.

Are there other (-W) options or switches which would create diagnostics for these cases?

like image 599
ensc Avatar asked Mar 16 '19 15:03

ensc


People also ask

What's wrong with _bool in C++?

This effectively reduces the compiler's ability to typecheck your program, since so many variables are pointers already, and C++ will happily stuff them into any bool argument to a function. It seems like the C99 _Bool type implements the same implicit type conversion brain damage.

Why is my Bool value 0x01 in C99?

In C99, bool is aliased to _Bool and if the flag is set, the above code will result in 'a' being 0x01 because of C99's requirements for type conversion. bool a = !! (someInt & 0x02) //'a' is now 0x01 when the bit is set.

Why is my GCC not optimizing my code?

This warning does not generally indicate that there is anything wrong with your code; it merely indicates that GCC’s optimizers are unable to handle the code effectively. Often, the problem is that your code is too big or too complex; GCC refuses to optimize programs when the optimization itself is likely to take inordinate amounts of time.

Why does GCC issue warnings when I use a common variable?

To help detect accidental misuses of such arrays GCC issues warnings unless it can prove that the use is safe. See Common Variable Attributes . Warn for cases where adding an attribute may be beneficial.


1 Answers

C defines the <stdbool.h> macros true and false as expanding to integer constant expressions of value 1 and 0 respectively. Since they're ints and bool (_Bool) in itself is an integer type, any such usage is equally valid. Even the value of the boolean expressions in C is an int and not a bool, so there is not much help for you with the bar function.

However, foo is a different beast - if the return value were true then it would be caught right away because 1 is not convertible to a pointer. false, having the integer constant value 0 is a null-pointer constant and will be converted to null pointer. You could perhaps catch the incorrect use by replacing the #include <stdbool.h> with something that does the inclusion but defines false as say 0.0 which is a falsy value but not an integer constant expression.

like image 147