在linux内核(版本4.8)中, " struct pid"定义如下(来自文件:http://lxr.free-electrons.com/source/include/linux/pid.h)。这里"数字[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),数组"数字"在for循环中是'数字[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 }
答案 0 :(得分:0)
是否可以使数组中的元素数量大于在编译时定义的数组大小?
是。它是调用未定义的行为,不应编写代码以允许它。
它是如何正确的,因为变量&#39; i&#39;不会导致分段错误,不能有零以外的任何值吗?
有可能;因为代码违反了合同。在数组边界外写可以工作。它可能会导致程序崩溃。它是未定义的行为。
未指定C 阻止数组访问其范围之外,也不会导致seg错误。可以捕获或不捕获这样的访问。代码本身需要负责确保访问在范围内 C
中没有指定training wheels和safety nets