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 output 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 doesn't initialize memory to zero. It returns it to you as it is without touching the memory or changing its value.
delete and free() in C++ In C++, the delete operator should only be used either for the pointers pointing to the memory allocated using new operator or for a NULL pointer, and free() should only be used either for the pointers pointing to the memory allocated using malloc() or for a NULL pointer. It is an operator.
malloc(0) does not allocate any memory. [EDITED: it can sometimes allocate memory, see my next answer] The return value of malloc (0) is implementation specific: it can return NULL or a valid pointer (some unique value) as in your case but memory is not allocated!!!
No, Linux does not zero its menory after releasing it. Most libraries implement zeroing the memory while allocating it, but this is programming language dependent and can be overridden.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With