奇怪的gcc警告行为

时间:2013-06-28 19:05:46

标签: c linux gcc

我正在开发一个linux驱动程序,我收到了这条警告信息:

/home/andrewm/pivot3_scsif/pivot3_scsif.c:1090: warning: ignoring return value of ‘copy_from_user’, declared with attribute warn_unused_result

违规行是:

  if (copy_from_user(tmp, buf, count) < 0)

在检查copy_from_user的声明后,我发现它返回unsigned long,所以显然比较总是会失败,所以返回值不会影响比较。那部分是有道理的,但为什么gcc也没有警告这是一个签名/无符号比较的事实?这仅仅是编译器的特点吗?或者它是否避免对同一表达式发出两次警告?

包含该行的函数是:

int proc_write(struct file *f, const char __user *buf, unsigned long count, void *data)
{
  char tmp[64];
  long value;
  struct proc_entry *entry;

  if (count >= 64)
    count = 64;
  if (copy_from_user(tmp, buf, count) < 0)
  {
    printk(KERN_WARNING "pivot3_scsif: failed to read from user buffer %p\n", buf);
    return (int)count;  
  }
  tmp[count - 1] = '\0';
  if (tmp[count - 2] == '\n')
    tmp[count - 2] = '\0';
  ...
}

在64位Red Hat上使用gcc 4.4.1(在公司服务器上,我真的无法选择升级)。

2 个答案:

答案 0 :(得分:4)

它似乎是一个编译器选项http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html

-Wno-unused-result
    Do not warn if a caller of a function marked with attribute warn_unused_result (see Function Attributes) does not use its return value. The default is -Wunused-result. 

....

-Wtype-limits
    Warn if a comparison is always true or always false due to the limited range of the data type, but do not warn for constant expressions. For example, warn if an unsigned variable is compared against zero with ‘<’ or ‘>=’. This warning is also enabled by -Wextra. 

答案 1 :(得分:3)

是的,这可能只是编译器的怪癖。该警告可能是在语法优化的几个步骤之后生成的,其中if()表达式被消除(因为条件总是为真),留下了裸函数调用。找到这种行为是相当常规的。同样有一些警告条件仅在使用优化启用进行编译时发出。

你似乎已经找到了适当的解决办法。

相关问题