Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

malloc zeroing out memory?

Tags:

c

malloc

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?

like image 763
endeavormac Avatar asked Oct 25 '09 21:10

endeavormac


People also ask

Does malloc zero memory?

malloc doesn't initialize memory to zero. It returns it to you as it is without touching the memory or changing its value.

How do I clear allocated memory with malloc?

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.

What happens if you malloc 0 bytes?

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!!!

Does Linux zero out memory?

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.


1 Answers

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).

like image 82
Robert Gamble Avatar answered Sep 17 '22 20:09

Robert Gamble