C语言中,如果数组成员在初始化的时候没有赋值,那么初始值是随机的吗?

问题描述 投票:0回答:1

我在阅读Linux 0.96a版本的源码/kernel/sched.c时, 我发现averunnable数组在初始化的时候并没有赋值,所以我想会不会导致它的数组成员的值在使用的时候变成了一个随机数。 源链接:https://elixir.bootlin.com/linux/0.96a/source/kernel/sched.c 第 355 行:unsigned long averunnable[3]; /* 定点数 */

  1. 我试着看了相关的源码,但是没找到这个averunnable数组是在哪里赋值的。
  2. 我试着运行这段代码,发现在使用这个数组成员时,初始值是随机的
# cat testaverunnable.c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

int main()
{

#define FSHIFT  11
#define FSCALE  (1<<FSHIFT)
/*
 * Constants for averages over 1, 5, and 15 minutes
 * when sampling at 5 second intervals.
 */
static unsigned long cexp[3] = {
        1884,   /* 0.9200444146293232 * FSCALE,  exp(-1/12) */
        2014,   /* 0.9834714538216174 * FSCALE,  exp(-1/60) */
        2037,   /* 0.9944598480048967 * FSCALE,  exp(-1/180) */
};
unsigned long averunnable[3];   /* fixed point numbers */

        int i, n=10;
        printf("before into for cycle, the averunnable [%u] is %u \n",i, averunnable[i]);

        for (i = 0; i < 3; ++i)
                {
                        printf("averunnable [%u] is %u \n",i, averunnable[i]);
                        averunnable[i] = (cexp[i] * averunnable[i] + n * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
                        printf("atfer calculation, the averunnable [%u] is %u \n",i, averunnable[i]);
                }

    return 0;
}
# gcc -o testaverunnable testaverunnable.c
# ./testaverunnable
before into for cycle, the averunnable [0] is 4195856 
averunnable [0] is 4195856 
atfer calculation, the averunnable [0] is 3861499 
averunnable [1] is 4195392 
atfer calculation, the averunnable [1] is 4126081 
averunnable [2] is 3756023344 
atfer calculation, the averunnable [2] is 3805055516 

这是Linus内核,所以我想我一定是忽略了什么,请帮助我,谢谢!

c linux linux-kernel scheduled-tasks
1个回答
1
投票

在未显式初始化的函数内部声明的变量具有 不确定的值。读取具有不确定值的变量会导致 undefined behavior。这种行为可以表现为读取“垃圾”值,尽管包括 0 在内的任何值都可以被视为“垃圾”,并且后续读取也可能导致看到不同的值。

但是,与您的示例代码不同,您引用的 Linux 内核代码确实not在函数内部声明

averunnable
,而是在文件范围内声明它。对于具有 static 存储持续时间 的变量,其中包括在文件范围内声明的变量,如果未显式初始化,它们将被初始化为 0(对于数字类型)或 NULL(对于指针类型)。

© www.soinside.com 2019 - 2024. All rights reserved.