C语言 malloc() 是否将分配的数组初始化为零?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45323930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is malloc() initializing allocated array to zero?
提问by devil0150
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;
}
The program doesn't print OK. mallocisn't supposed to initialize the allocated memory to zero. Why is this happening?
该程序不打印OK。malloc不应该将分配的内存初始化为零。为什么会这样?
回答by msc
The man page of mallocsays:
malloc的手册页说:
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() 函数分配 size 字节并返回指向已分配内存的指针。内存未初始化。如果 size 为 0,则 malloc() 返回 NULL 或稍后可以成功传递给 free() 的唯一指针值。
So, malloc()returns uninitialized memory, the contents of which is indeterminate.
因此,malloc()返回未初始化的 memory,其内容不确定。
if (arr[i] != 0)
In your program, You have tried to access the content of a memory block, which is invoked undefined behavior.
在您的程序中,您尝试访问内存块的内容,该内容被调用为undefined behavior。
回答by haccks
malloc isn't supposed to initialize the allocated memory to zero.
malloc 不应该将分配的内存初始化为零。
Memory allocated by mallocis uninitialised. Value at these locations are indeterminate. In this case accessing that memory can result in an undefined behavior if the value at that location is to be trap representation for the type.
分配的内存malloc未初始化。这些位置的价值是不确定的。在这种情况下,如果该位置的值是该类型的陷阱表示,则访问该内存可能会导致未定义的行为。
n1570-§6.2.6.1 (p5):
n1570-§6.2.6.1 (p5):
Certain object representations need not represent a value of the object type. If the stored value of an object has such a representation and is read by an lvalue expression that does not have character type, the behavior is undefined. [...]
某些对象表示不需要表示对象类型的值。如果对象的存储值具有这样的表示形式并且被没有字符类型的左值表达式读取,则行为未定义。[...]
and footnote says:
和脚注说:
Thus, an automatic variable can be initialized to a trap representation without causing undefined behavior, but the value of the variable cannot be used until a proper value is stored in it.
因此,可以将自动变量初始化为陷阱表示,而不会导致未定义的行为,但只有在其中存储了适当的值后才能使用该变量的值。
Nothing good can be expected if the behavior is undefined.You may or may not get expected result.
如果行为未定义,则不会有任何好处。您可能会也可能不会得到预期的结果。
回答by axiac
mallocisn't supposed to initialize the allocated memory to zero. Why is this happening?
malloc不应该将分配的内存初始化为零。为什么会这样?
This is how it was designed more than 40 years ago.
40 多年前,它就是这样设计的。
But, on the same time, there was created the calloc()function that initializes the allocated memory to zeroand it's the recommended way to allocate memory for arrays.
但是,与此同时,创建了将分配的内存初始化为零的calloc()函数,这是为数组分配内存的推荐方法。
The line:
线路:
arr = (int *)malloc(sz * sizeof(int));
Should read:
应该读:
arr = calloc(sz, sizeof(int));
If you are learning C from an old book it teaches you to always cast the value returned by malloc()or calloc()(a void *) to the type of the variable you assign the value to (int *in your case). This is obsolete, if the value returned by malloc()or calloc()is directly assigned to a variable, the modern versions of C do not need that cast any more.
如果您从一本旧书中学习 C,它会教您始终将malloc()or calloc()(a void *)返回的值强制转换为您为其分配值的变量的类型(int *在您的情况下)。这是过时的,如果返回的值malloc()或calloc()直接分配给变量,则现代版本的 C 不再需要该转换。
回答by Ryan B.
From the C Standard 7.22.3.4:
来自 C 标准 7.22.3.4:
Synopsis
概要
#include <stdlib.h>
void *malloc(size_t size);
Description
描述
The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate.
malloc 函数为大小由 size 指定且值不确定的对象分配空间。
The value is indeterminate. So, every compiler is free to behave how it wants. For example, in Microsoft Visual C++, in Debugmode, the area of allocated memory by malloc()is all set to 0xCDCDCDCDand when in Releasemode it is random. In modern versions of GCC, it is set to 0x000000 if you don't enable code optimizations, and random otherwise. I don't know about other compilers, but you get the idea.
该值是不确定的。因此,每个编译器都可以自由地按照自己的意愿行事。例如,在 Microsoft Visual C++ 中,在Debugmode 下,分配的内存区域由malloc()全部设置为,0xCDCDCDCD并且在Releasemode 下它是随机的。在现代版本的 GCC 中,如果不启用代码优化,则设置为 0x000000,否则设置为随机。我不知道其他编译器,但你明白了。
回答by Luis Colorado
The first time you call malloc(3), it asks to the operating system to get memory for the heap space.
第一次调用时malloc(3),它会要求操作系统为堆空间获取内存。
For security reasons, the unix/linux kernel (and many other operating systems) in general zeroes the page contents that is to be given to a process, so no process can access that memory's previous contents and do nasty things with it (like searching for old passwords, or similar things).
出于安全原因,unix/linux 内核(以及许多其他操作系统)通常会将要提供给进程的页面内容归零,因此没有进程可以访问该内存的先前内容并对其进行操作(例如搜索旧密码或类似的东西)。
If you do several allocations and deallocations of memory, when the malloc module reuses the previous memory, you'll see garbage coming from malloc(3).
如果你对内存进行多次分配和释放,当 malloc 模块重用之前的内存时,你会看到来自malloc(3).
回答by babon
void *malloc(size_t size)is just supposed to keep aside the specified amount of space. That's all. There is no guarantee as to what will be present in that space.
void *malloc(size_t size)只是应该保留指定的空间量。就这样。无法保证该空间中将出现什么。
Quoted from the man pages:
引自手册页:
The
malloc()function allocates size bytes and returns a pointer to the allocated memory. The memory is not initialized. Ifsizeis 0, thenmalloc()returns either NULL, or a unique pointer value that can later be successfully passed tofree().
该
malloc()函数分配 size 字节并返回指向分配内存的指针。内存未初始化。如果size为 0,则malloc()返回 NULL 或稍后可以成功传递给 的唯一指针值free()。
Apart from calloc()you can use the memset()function to zero out a block of memory.
除了calloc()您可以使用该memset()功能将内存块清零。
回答by kalaiamuthan manisekar
Zero's are assigned to page contents at first time in linux kernel.
在 linux 内核中第一次为页面内容分配零。
Below program explains the memory initialisation difference in malloc and calloc:
下面的程序解释了 malloc 和 calloc 中内存初始化的区别:
#include<stdio.h>
#include<stdlib.h>
#define SIZE 5
int main(void) {
int *mal = (int*)malloc(SIZE*sizeof(int));
int *cal = (int*)calloc(SIZE, sizeof(int));
mal[4] = cal[4] = 100;
free(mal); free(cal);
mal = (int*)malloc(SIZE*sizeof(int));
cal = (int*)calloc(SIZE, sizeof(int));
for(int i=0; i<SIZE; i++) {
printf("mall[%d] = %d\n", i, mal[i]);
}
for(int i=0; i<SIZE; i++) {
printf("call[%d] = %d\n", i, cal[i]);
}
}

