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!
After digging deep into the gcc manual:
As some other posters wrote, -Wextra should do it
Sample code:
Try -Wextra
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.
As an alternative to the compiler, I find that running an autoindenter over the code helps find these situations.
In vim for example: