处理数组越界或负数组索引的最佳方法

时间:2018-04-12 07:23:14

标签: c arrays

我已经定义了一个映射到字符串数组的枚举。我将此字符串作为函数的参数,该函数将返回枚举值。该值用作另一个数组的索引。

功能看起来像这样

int get_unit_id(char * name);

如果在数组中找不到名称,则函数返回-1。虽然这种情况在当前的设置中从未出现过,但静态分析工具却抛出一个错误,即数组索引可能是负数。我该如何处理?

我还考虑过返回枚举的MAX元素的ID,但这会导致数组越界警告

编辑:添加代码以供参考。 检查函数的返回值是不可行的,因为从很多地方调用函数,它会大量增加LOC的数量。

int get_unit_id(const char * name)
   {
       int index;

       for (index = 0; index < UNIT_MAX_UNITS; index++){
           if(!strcmp(name, unit_map[index].unit_name)){
               return unit_map[index].unit_id;
           }
       }
       printf("Didn't find Unit %s, returning -1\n",name);
       return -1;
  }

1 个答案:

答案 0 :(得分:1)

如果在将结果用作数组索引之前没有检查结果是否为负,静态分析工具正确地标记了否定索引的可能用途。

如果您将数组的特殊元素作为未知名称的catch-all并返回该值的索引而不是-1,则可以解决此问题。

例如:

struct map {
    char *unit_name;
    int unit_id;
};

struct map unit_map[UNIT_MAX_UNITS+1] = {
    { "value_0", 0 },
    { "value_1", 1 },
    ...
    { "value_UNIT_MAX_UNITS-1", UNIT_MAX_UNITS-1 },
    { "unknown", UNIT_MAX_UNITS },
};

然后在你的函数中:

int get_unit_id(const char * name)
{
   int index;

   for (index = 0; index < UNIT_MAX_UNITS; index++){
       if(!strcmp(name, unit_map[index].unit_name)){
           return unit_map[index].unit_id;
       }
   }
   printf("Didn't find Unit %s, returning UNIT_MAX_UNITS\n",name);
   return unit_map[UNIT_MAX_UNITS].unit_id;
}