malloc zeroing out memory?
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.