Please examine the following code:
if (foo->bar == NULL);
foo->bar = strdup("Unknown");
I spent the last part of three hours hunting down that leak with Valgrind, feeling very silly when I discovered the bogus ';'.
I know that the above code is valid C, however I would love for gcc to be able to tell me if I'm using a conditional as a statement.
Is there a flag that I could pass which would help spot this type of mistake in the future? It seems to me that gcc would be able to know if a conditional is useless.
IE:
if (1 == 1);
code_that_is_always_reached_since_conditional_is_a_statement();
None of the lints take issue with this either. Valgrind is great to find these kinds of things .. but the leak was actually much later in the code than where the pointer was originally allocated.
Any help is appreciated, even "No, it doesn't do that."
Edit:
Wow, thanks for such a fast and great response! To summarize, here are your options:
Some people might find -Wextra annoying. You may have a comparison between types of different signedness, but you know the comparison happens only when they are the same.
i.e.
int ret;
unsigned int i;
ret = foo(bar); /* foo() is known to return a signed errno on failure */
if (ret < 0)
return 1;
/* Enter GCC complaining that ret differs in signedness
* (but you know it doesn't and get the urge to cast it) */
for (i = 0; i < ret; i ++)
...
Thanks again for the tips!
/* foo.c */
int main() {
if (1) ;
return 0;
}
gcc -Wextra -c foo.c
foo.c: In function ‘main’:
foo.c:2: warning: empty body in an if-statement
After digging deep into the gcc manual:
-Wempty-body
Warn if an empty body occurs in an `if', `else' or `do while' statement. This warning is also enabled by
-Wextra.
As some other posters wrote, -Wextra should do it
Sample code:
int main(){
if (0);
printf("launch missiles");
return 0;
}
$gcc -Wempty-body foo.c
warn.c: In function ‘main’:
warn.c:5: warning: suggest braces around empty body in an ‘if’ statement
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With