可以gcc的准确把握无用的条件语句? [英] Can gcc accurately catch useless conditionals?

查看:276
本文介绍了可以gcc的准确把握无用的条件语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请检查下面code:

 如果(foo->酒吧== NULL);
   foo->巴=的strdup(未知);

我花了三小时的最后一部分追捕与这Valgrind的泄漏,感觉非常傻了,当我发现的假;

我知道,上面的code是合法的C,但是我很想为gcc才能如果我使用条件作为语句来告诉我。

有没有办法,我可以通过它能够帮助我们发现在未来这种类型的错误的一个标志?这在我看来,海合会将能够知道,如果有条件也没用。

IE

 如果(1 == 1);
  code_that_is_always_reached_since_conditional_is_a_statement();

在lints没有采取这个问题无论是。 Valgrind是伟大的发现这类东西..但泄漏实际上是在code比在指针最初分配的要晚得多。

任何帮助是AP preciated,甚至不,它不会做。

编辑:

哇,感谢这么快,很大的反响!总之,您有以下选项:


  • -Wextra对各种事情拿起了-Wall不包括
    空/无用语句。

  • -Wempty体回升对无用的报表,这是启用
    -Wextra(但可以打破旧版本的gcc,适用于4.3.x版)

有些人可能会发现-Wextra讨厌。您可能有不同类型的符号性之间的比较,但你的了解的比较只发生时,他们是相同的。

  INT RET;
无符号整型我;RET = foo的(巴); / * foo的()是众所周知的在失败时返回一个错误号签* /
如果(RET℃下)
  返回1;/ *输入GCC抱怨RET的符号性的区别
 *(但你知道它不并得到冲动投它)* /
对于(i = 0; I< RET;我++)
   ...

的提示再次感谢!


解决方案

  / * foo.c的* /
诠释主(){
   如果(1);
   返回0;
}GCC -Wextra -c foo.c的
foo.c的:在函数'主':
foo.c的:2:警告:体为空if语句

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!

解决方案

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

这篇关于可以gcc的准确把握无用的条件语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆