0

我正在从 Coverity 问题中清理一些代码,并且遇到这样一种情况,即较早使用指向函数的本地指针是用于比较的函数,然后将其分配给指向 else 的位置,但它从未被取消引用或使用将某物赋予其价值。Coverity 是说它是一个未使用的指针值 - 所以我想将它转换为 void 以指示该指针在该点之后未使用。我想知道什么时候考虑在程序中使用值或变量?这是解释我的情况的代码示例:

在下面的示例中,Coverity 会将 fltr_ptr 标记为在示例结束时的两次分配之后未使用

int initialise (void) 
{
    // pointer first decalred and defined
    FILTER_PTR  fltr_ptr = NULL;

    // pointer given valid value
    fltr_ptr = global_val->filter_group[index];

    // second use of fltr_ptr 
    if ( TRUE == fltr_ptr -> being_used)
    {
        // first use of fltr_ptr 
        if ( TRUE != close_filter ( fltr_ptr -> Filter)
        {
            // print error
        }
        // do more code

        // fltr_ptr assigned first time , value not used should it be (void)fltr_ptr?
        fltr_ptr = Free_Memory (fltr_ptr, sizeof(FILTER_PTR));
    }
    else
    {
        return 1;
    }

    for ( number of iterations )
    {
        // fltr_ptr assigned again but value not used should it be (void)fltr_ptr?
        fltr_ptr = global_val->filter_group[index];
    }
    return 0;
}
4

2 回答 2

4

Coverity 指向您fltr_ptr在最后一个for循环中分配给您的内容,但您对此值不执行任何操作。为什么要分配?转换为 void 可能会修复警告,但首先要修复的应该是以某种方式使用指针,或者停止分配给它。

于 2014-10-21T10:18:59.300 回答
1

为了回答标题问题,当“它被初始化或分配给然后处置而不被读取”时,变量被认为是未使用的。

int main()
{
    int i;
    int j = 1;     // both i and j are unused at this point

    int i = j * 2; // j is now 'used', the new value of i is unused
    printf("%d",j);//j is used again
}                  // i goes out of scope without being used.

请注意,该定义也不是“如果在没有被读取的情况下分配给它”,因为这表明以下内容存在问题:

unsigned int find_max_index(int a[], int size)
{
    unsigned int i;
    unsigned int maxval   = 0;
    unsigned int maxindex = 0;
    for (i = 0; i< size; i++){
        if (a[i]>maxval){
            maxval = a[i];
            maxindex = i;
        }
    }
    return maxindex;
}

如在此代码maxindex中,可以多次分配而不被读取。

回顾我原来的例子,我们可以i在不改变程序的情况下消除。这降低了程序的复杂性,消除了冗余操作(尽管编译器在优化时也应该这样做)并减少将来程序员出错的机会:

//FUNCTIONALLY THE SAME AND SIMPLER
int main()
{
    int j = 1;     // j is unused at this point
    printf("%d",j);// j is used
}

同样,您可以删除整个循环:

for ( number of iterations )
{
    // fltr_ptr assigned again but value not used should it be (void)fltr_ptr?
    fltr_ptr = global_val->filter_group[index];
}

(您删除分配并得到一个空循环。因为这是一个很长的 nop,它也可以被删除)

于 2014-10-21T14:10:37.060 回答