简体   繁体   English

如何解决多空间警告“数组索引超出范围

[英]How to solve polyspace warning "array index out of bounds

While doing Poly-space analysis on the code base, I am getting an orange check warning on below snippet saying that the pointer may be outside its bounds.在对代码库进行多空间分析时,我在下面的代码片段上收到一个橙色检查警告,指出指针可能超出了它的范围。

I've tried adding a null check before accessing the array like if( x[i] != NULL), but it doesn't help.The pointer which is passed as an argument to the function is also declared as a pointer, so that I'm not able to determine the size of buffer being passed to the function.我尝试在访问 if( x[i] != NULL) 之类的数组之前添加一个空检查,但这没有帮助。作为参数传递给函数的指针也被声明为指针,所以我无法确定传递给函数的缓冲区大小。

void foo(const int *x, unsigned int value)
{
   int i, data;
   for(i=0;i<value;i++)
   {
      data = x[i]; // pointer may be out of bounds here
   }
   sendToSomeOtherInterface(data);
}

I can understand that polyspace might be assuming that at some point of time, the pointer may point to an invalid memory and code may crash, but how to write code more cleanly to avoid the problem?我可以理解 polyspace 可能会假设在某个时间点,指针可能指向无效的内存并且代码可能会崩溃,但是如何更干净地编写代码以避免问题? I can't change usage of pointers as it has an impact over huge files.我无法更改指针的使用,因为它对大文件有影响。

How Polyspace handles this depends on the context of the analysis. Polyspace 如何处理这取决于分析的上下文。 If you run just that function through on its own, and depend on Polyspace's main generator, then I would expect that to be an orange out of bounds array index on line 6.如果您只运行该函数并依赖于 Polyspace 的主生成器,那么我希望它是第 6 行的橙色越界数组索引。

A few things to consider:有几点需要考虑:

  1. This code breaks at least a few common industry coding guidelines regarding usage of pointers and arrays.此代码至少违反了一些关于指针和数组使用的常见行业编码准则。
  2. In order for Polyspace to know that index i is going to be within the bounds of the buffer pointed to by the constant pointer x , Polyspace will need to be able to know the size of the buffer represented by x .为了让 Polyspace 知道索引i将在常量指针x指向的缓冲区的范围内,Polyspace 需要能够知道由x表示的缓冲区的大小。
  3. Without any calling context (using main generator and no explicit calls to this function), Polyspace is going to be stuck in the situation of not knowing the bounds of x or the value of value .如果没有任何调用上下文(使用主生成器并且没有显式调用此函数),Polyspace 将陷入不知道x的边界或 value 的value的情况。 This is true for anyone on stackoverflow just reading the code without context as well.这对于任何使用 stackoverflow 的人来说都是如此,只是在没有上下文的情况下阅读代码。
  4. If you analyze the function with calling context, that code may provide enough information.如果您使用调用上下文分析函数,则该代码可能会提供足够的信息。 Ultimately, Polyspace has to be able to see the size of what is passed in via the constant pointer x最终,Polyspace 必须能够看到通过常量指针x传入的内容的大小

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM