gpt4 book ai didi

c - 数组中的元素数量是否可能超过编译时定义的数组大小?

转载 作者:IT王子 更新时间:2023-10-29 00:43:52 28 4
gpt4 key购买 nike

<分区>

在 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”作为“numbers[i]”在 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 }

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com