开发者

malloc zeroing out memory?

Given this C code compiled with gcc 4.3.3

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

 
int main(int argc, char * argv[])
{
 
    int * i;
    
    i = malloc(sizeof(int));
    
    printf("%d\n", *i);
    return 0;
 
}

I would expect the outpu开发者_开发知识库t to be whatever was in the memory that malloc() returns, but instead the output is 0. Is malloc zeroing out the memory it returns? If so, why?


malloc itself doesn't zero out memory but it many operating systems will zero the memory that your program requests for security reasons (to keep one process from accessing potentially sensitive information that was used by another process).


The malloc() function does not set the allocated memory to any specific value. If you want to make sure the memory is zero, use calloc() or equivalent. Otherwise, you get whatever what was there before (which might, in your case, be zero).


The value in the allocated memory is officially undefined. C99 states: The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate. malloc() can do whatever it wants, including zeroing it out. This may be deliberate, a side-effect of the implementation, or you might just have a lot of memory that happens to be 0.

FWIW on OS X with Apple's gcc 4.0.1 I can't make it come out not 0 even doing a lot of allocations:

for( idx = 0; idx < 100000; idx++ ) {
    i = (int *) malloc(sizeof(int));
    printf("%d\n", *i);
}


Malloc does not have to fill memory. For performance reasons, the release versions often do nothing with memory. A "secure" library may have a malloc implementation which clears memory. It is up to the library implementer. There are some common patterns that are filled into memory by various compiler's debug libraries that are explained in this stackoverflow topic.


You definitely can't depend on it being 0. malloc a larger chunk and dump it to see.


Whether its int; int=0; or int=00000000; its going to take up the same space in memory. the printf will often catch the first 0 as a null terminator regardless of what else is in the string. If you are using string comparators and 0 is a placeholder I would recommend you use ANYTHING but 0 for that place holder as string based libraries really suck. Try F and then write the control in yourself inserting null term or newline as need be it will be way more portable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜