是malloc()将分配的数组初始化为零吗? [英] Is malloc() initializing allocated array to zero?
问题描述
这是我正在使用的代码:
Here is the code I'm using:
#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;
}
程序不打印OK
. malloc
不应将分配的内存初始化为零.为什么会这样?
The program doesn't print OK
. malloc
isn't supposed to initialize the allocated memory to zero. Why is this happening?
推荐答案
malloc()函数分配大小字节并返回指向 分配的内存. 内存未初始化.如果大小为0, 然后malloc()返回NULL或可以 稍后将其成功传递给free().
The malloc() function allocates size bytes and returns a pointer to the allocated memory. The memory is not initialized. If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().
因此,malloc()
返回未初始化的内存,其内容是不确定的.
So, malloc()
returns uninitialized memory, the contents of which is indeterminate.
if (arr[i] != 0)
在您的程序中,您试图访问内存块的内容,该内存块被调用未定义的行为.
In your program, You have tried to access the content of a memory block, which is invoked undefined behavior.
这篇关于是malloc()将分配的数组初始化为零吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!