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

qv7cva1a  于 2023-04-29  发布在  其他
关注(0)|答案(1)|浏览(113)

当我在阅读源代码/kernel/sched的时候。Linux 0的C。96 a版本中,我发现averunnable数组在初始化时没有赋值,所以我想知道这是否会导致其数组成员的值在使用时变成随机数。源链接:第355行:unsigned long averunnable[3];/* 固定点数 */
1.我试图阅读相关的源代码,但我没有找到这个avernable数组被赋值的位置。
1.我试着运行这段代码,发现当使用这个数组成员时,初始值是随机的。

# 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内核,所以我想我一定是忽略了什么,请帮助我,谢谢!

woobm2wo

woobm2wo1#

在函数内部声明的变量如果没有显式初始化,则具有不确定的值。阅读具有不确定值的变量可能导致undefined behavior。这种行为可以表现为阅读“垃圾”值,尽管包括0的任何值都可以被认为是“垃圾”,并且后续读取也可能导致看到不同的值。
但是,与示例代码不同,您引用的Linux内核代码并没有在函数内部声明averunnable,而是在文件范围内声明。对于具有 static storage duration 的变量,包括在文件范围内声明的变量,如果没有显式初始化,则将其初始化为0(对于数值类型)或NULL(对于指针类型)。

相关问题