1

I was playing around with alloc functions in my Ubuntu 14.04 64-bit, gcc version 4.8.2 (Ubuntu 4.8.2-19ubuntu1) and found that malloc returns memory with initializing it to zero. Which is quite weird as it should not initialize and the returned memory block should be uninitialized.

The code is as follows:

#include<stdio.h>
#include<stdlib.h> 
int main()
{
    int *i=(int*)malloc(4);
    printf("The Address of pointer is %p and Value is %d\n",i,*i);
    return 0;
}

Output is:

The Address of pointer is 0x843070 and Value is 0  

I have also tried with assigning big chunks of memory with the same result. Can anyone suggest why this is happening?

2
  • "I have also tried with assigning big chunks of memory" ... You looped through all the words in the chunk you got and tested if they were zero?
    – muru
    Apr 13, 2015 at 20:24
  • Yes, initially I tried with 40byte and latter 80bytes ND printed the values.
    – SKY
    Apr 14, 2015 at 18:50

1 Answer 1

2

malloc() allocates memory from the heap, which it manages. It very well may return a chunk of heap that was previously used and then free()ed, and so it will still contain whatever data was there before. When there is no heap yet, or not any free, it has to obtain more ram from the kernel to enlarge the heap. When the kernel gives a new process more ram, it makes sure to zero it all out first, lest one process be able to capture and examine data freed by another process, which may contain sensitive information. Thus, what you are likely seeing is the first time you malloc() any memory, it is coming straight from the kernel and is thus zeroeod, rather than being reused heap within the process, which would not be zeroed.

1
  • to put it simply, malloc does not initialize the memory is allocates. However, calloc does initialize the memory to all '\0' Apr 14, 2015 at 22:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .