c - 静态常量数组中的出站访问

标签 c arrays undefined-behavior

假设以下代码:

static const value_string global_variable [] = {
        { 4,   "STRING1" },              
        { 6,   "STRING2" },
        { 9,   "STRING3" },
        { 10,  "STRING4" },
        { 11,  "STRING5" },
        { 12,  "STRING6" },
        { 13,  "STRING7" },
        { 14,  "STRING8" },
        { 15,  "STRING9" },
};

const gchar * try_val_to_str_idx(const guint32 val, const value_string *vs, gint *idx)    
{
   gint i = 0;
   DISSECTOR_ASSERT(idx != NULL); 
   if(vs) {
      while (vs[i].strptr) {
         if (vs[i].value == val) {
            *idx = i;
            return(vs[i].strptr);
         }
         i++;
      }
    }

   *idx = -1;
   return NULL;
}

其中 vs 是一个静态 const 数组 (global_variable ),其结构具有两个元素: 一个 int 和一个指向 char 的指针。

此代码是wireshark源代码的摘录。因此,该函数假设 vs 是一个 static const 变量。

我的问题是,我是否可以假设访问静态 const 数组的出站索引(我猜它存储在 .DATA 段上)是有效的?是否可以访问有效的内存位置?或者是未定义的行为?

例如,如果我尝试查找与值 40 相关的字符串,会发生什么情况? 如果它有效,我如何确定该内存位置将具有 0 值,然后 NULL 并退出 while 循环?

最佳答案

can i assume that accessing an outbound index of a static const array (that i guess is stored on the .DATA segment) is valid?

访问越界内存总是 undefined behaviour 。甚至不要尝试这样做。

关于c - 静态常量数组中的出站访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32093644/

相关文章:

python ctypes - 包装空指针

c - 如何删除 typedef 结构数组?

调用从 Ada 返回数组的 C 函数

java - 如何将扫描仪输入拆分为(数字)(带空格的字符串)(数字)

c++ - 是否将正确对齐和大小的数组转换和访问到未构造的平凡类型未定义行为?

c - 使用 scanf 获取用户的多个输入

php - 获取所有可能的组合而不重复

javascript - 操作两个单独数组中的数组键值

c++ - 堆分配的 const 对象与非 const 对象有何不同?

rust - ManuallyDrop<Box<T>> 是否具有 mem::uninitialized 定义的行为?