加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

是否有可能在数组中包含多个元素,而不是在编译时定义的数组大小

发布时间:2020-12-16 06:52:58 所属栏目:百科 来源:网络整理
导读:参见英文答案 What’s the need of array with zero elements?????????????????????????????????????5个 在linux内核(版本4.8)中, “struct pid”定义如下(来自文件: http://lxr.free-electrons.com/source/include/linux/pid.h).这里“numbers [1]”(第64
参见英文答案 > What’s the need of array with zero elements?????????????????????????????????????5个
在linux内核(版本4.8)中,
“struct pid”定义如下(来自文件: http://lxr.free-electrons.com/source/include/linux/pid.h).这里“numbers [1]”(第64行)是一个静态数组,它只能有一个元素(因为数组大小被提到为1).

57 struct pid
 58 {
 59         atomic_t count;
 60         unsigned int level;
 61         /* lists of tasks that use this pid */
 62         struct hlist_head tasks[PIDTYPE_MAX];
 63         struct rcu_head rcu;
 64         struct upid numbers[1];
 65 };

但是,在第319行和第320行的以下代码中(来自文件:http://lxr.free-electrons.com/source/kernel/pid.c),数组“numbers”在for循环中作为’numbers [i]’.它是如何甚至是正确的,因为变量’i’在没有导致分段错误的情况下不能具有零以外的任何值?我已经在循环期间检查了’i’的值,看它是否超过1.是的,它仍然没有看到任何分段错误.我错过了什么吗?

297 struct pid *alloc_pid(struct pid_namespace *ns)
298 {
299         struct pid *pid;
300         enum pid_type type;
301         int i,nr;
302         struct pid_namespace *tmp;
303         struct upid *upid;
304         int retval = -ENOMEM;
305 
306         pid = kmem_cache_alloc(ns->pid_cachep,GFP_KERNEL);
307         if (!pid)
308                 return ERR_PTR(retval);
309 
310         tmp = ns;
311         pid->level = ns->level;
312         for (i = ns->level; i >= 0; i--) {
313                 nr = alloc_pidmap(tmp);
314                 if (nr < 0) {
315                         retval = nr;
316                         goto out_free;
317                 }
318 
319                 pid->numbers[i].nr = nr;
320                 pid->numbers[i].ns = tmp;
321                 tmp = tmp->parent;
322         }

解决方法

Is it possible to have number of elements in an array more than array’s size which is defined at compile time?

是.它是调用未定义的行为,不应编写代码以允许它.

How is it even correct because variable ‘i’ cannot have any value other than zero without causing segmentation fault?

有可能的;因为代码违反了合同.在数组边界外写可能有效.它可能会导致程序崩溃.这是未定义的行为.

未指定C以防止在其边界之外的数组访问也不会导致seg错误.可以捕获或不捕获这样的访问.代码本身需要负责确保访问在范围内.
C中没有指定training wheels和少数safety nets

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读