Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can gcc accurately catch useless conditionals?

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:

  • -Wextra picks up on all kinds of things that -Wall does not, including empty / useless statements.
  • -Wempty-body picks up on useless statements, which is enabled by -Wextra (but can break older versions of gcc, works on 4.3.x)

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!

like image 636
Tim Post Avatar asked May 12 '09 04:05

Tim Post


2 Answers

/* 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
like image 167
Employed Russian Avatar answered Sep 20 '22 08:09

Employed Russian


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
like image 26
Tom Avatar answered Sep 21 '22 08:09

Tom