gpt4 book ai didi

c - malloc() 是否将分配的数组初始化为零?

转载 作者:太空狗 更新时间:2023-10-29 17:04:45 26 4
gpt4 key购买 nike

这是我使用的代码:

#include <stdio.h>
#include <stdlib.h>

int main() {
int *arr;
int sz = 100000;
arr = (int *)malloc(sz * sizeof(int));

int i;
for (i = 0; i < sz; ++i) {
if (arr[i] != 0) {
printf("OK\n");
break;
}
}

free(arr);
return 0;
}

程序不打印OKmalloc 不应将分配的内存初始化为零。为什么会这样?

最佳答案

malloc isn't supposed to initialize the allocated memory to zero. Why is this happening?

这就是 40 多年前的设计方式。

但是,与此同时,calloc()创建的函数将分配的内存初始化为零,这是为数组分配内存的推荐方法。

行:

arr = (int *)malloc(sz * sizeof(int));

应阅读:

arr = calloc(sz, sizeof(int));

如果您是从一本旧书中学习 C,它会教您始终转换 malloc()calloc() 返回的值(a void * ) 到您为其赋值的变量的类型(在您的情况下为 int *)。这是过时的,如果将 malloc()calloc() 返回的值直接分配给变量,则现代版本的 C 不再需要该转换。

关于c - malloc() 是否将分配的数组初始化为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45323930/

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