Can gcc accurately catch useless conditionals?

2019-02-05 23:50发布

问题:

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!

回答1:

/* 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


回答2:

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


回答3:

Try -Wextra



回答4:

As an alternative to the compiler, I find that running an autoindenter over the code helps find these situations.

In vim for example:

gg=G


回答5:

In addition to the above, if you find yourself getting frustrated hunting for a bug using valgrind or a similar execution profiler, you should perhaps consider using a static analysis tool, such as lint. Personally, I use PC-LINT, which catches all sorts of these types of bugs.