鉴于这段C代码是用gcc 4.3.3编译的
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char * argv[])
{
int * i;
i = (int *) malloc(sizeof(int));
printf("%d\n", *i);
return 0;
}
我希望输出是malloc()返回的内存中的内容,但实际上输出是0。malloc是否正在清零它返回的内存?如果有,原因何在?
发布于 2009-10-25 21:56:47
malloc
本身不会清零内存,但许多操作系统会出于安全原因将您的程序请求的内存清零(以防止一个进程访问另一个进程使用的潜在敏感信息)。
发布于 2009-10-25 21:50:51
malloc()
函数不会将分配的内存设置为任何特定值。如果要确保内存为零,请使用calloc()
或等效的内存。否则,您将得到以前存在的内容(在您的情况下,可能为零)。
发布于 2009-10-25 22:03:35
分配的内存中的值是正式未定义的。C99声明:The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate.
malloc()可以做它想做的任何事情,包括将其置零。这可能是故意的,可能是实现的副作用,或者您可能只是有大量的内存恰好是0。
在OS上的FWIW和苹果的gcc 4.0.1我不能让它出来,甚至不是0,甚至做了很多分配:
for( idx = 0; idx < 100000; idx++ ) {
i = (int *) malloc(sizeof(int));
printf("%d\n", *i);
}
https://stackoverflow.com/questions/1622196
复制相似问题