Coverity警告局部变量的默认初始化

时间:2015-06-11 07:17:16

标签: c coverity

有一个覆盖警告类型:UNUSED_VALUE。这是由"代码可维护性问题"

下的工具定义的

UNUSED_VALUE:当为变量分配从函数调用返回的指针值并且从不在源代码中的任何其他位置使用时,它不仅会导致资源的低效使用,还会导致未确定的行为。此检查程序会在为其分配值后识别程序中任何其他位置从未使用过的所有变量。

这个检查器似乎也在采取一些好的编程实践作为警告。

我的问题是,是否有更好的方法来做这些事情?或者应该忽略这样的警告(并向Coverity团队报告任何可能的改进)?

示例1:局部变量的默认初始化

int func()
{
   int retval = SUCCESS;  //COVERITY says: Unused value     (UNUSED_VALUE)assigned_value: Value SUCCESS is assigned to retval here, but that     stored value is not used before it is overwritten

   retval = recvMessage();  //COVERITY says: value_overwrite: Value SUCCESS     is overwritten with value fromrecvMessage

   ....

}

示例2:释放内存后将指针设置为NULL

void func2()
    {
       char *p = NULL;
       ....
       p = alloc_mem_wrapper();
       ... do something
       free_mem_wrapper(p);
       p = NULL; //Coverity says: Unused value (UNUSED_VALUE)assigned_pointer: Value NULL is assigned to p here, but that stored value is not used    
       ... do rest of the job (p is not used again)
    }

就我而言,所有警告中有90%仅属于上述性质!

2 个答案:

答案 0 :(得分:0)

为什么不这样做:

int retval = recvMessage();

和这个

char * p = alloc_mem_wrapper();

(主要)如果你不知道如何初始化你可能不需要的变量(你定义它的地方)。

答案 1 :(得分:0)

以上所有建议都是好的,但仍然有人会偶然发现此错误并将其视为问题。我猜人们将其与违反良好做法相关联,因为他们认为它将在以下情况下出现

start /B name_mdl.exe -u input_1.txt -o output_1.mat >>report_1.txt
printf('%d case completed',num_case);
start /B name_mdl.exe -u input_2.txt -o output_2.mat >>report_2.txt
printf('%d case completed',num_case);

在上面,声明状态并在它们之间的代码更新后立即打印就可以了。但是,在这种情况下,Coverity不会报告它UNUSED_VALUE。它实际上抱怨以下代码

int status = -1;
char c = getch();

switch(c){
    case 'w': {
        status = walk();
    }
    break;
    case 's': {
        status = sit();
    }
    break;
}

printf("Status %d\n", status);

以上,int status = -1; int steps = 0; char c = getch(); switch(c){ case 'w': { status = walk(); steps = get_steps(); status = (steps > 0)?status:-1; } break; case 's': { status = sit(); } break; } printf("Status %d\n", status); 可以简单地是一个范围变量。因此,Coverity错误与作用域有关,而不是初始化。