linux - [Solved-5 Solutions] Why does malloc initialize the values to 0 in gcc - ubuntu - red hat - debian - linux server - linux pc
Linux - Problem :
Why does malloc initialize the values to 0 in gcc ?
Linux - Solution 1:
- The OS will usually clear fresh memory pages it sends to your process so it can't look at an older process' data.
- This means that the first time you initialize a variable (or malloc something) it will often be zero but if you ever reuse that memory then all bets are off.
- As for the unwanted performance overheads, avoiding unspecified behaviour is probably more important.
- Whatever small performance boost you could gain in this case won't compensate the hard to find bugs you will have to deal with if someone slightly modifies the codes or ports it to another system.
Linux - Solution 2:
- The malloc() function allocates size bytes and returns a pointer to the allocated memory.
- The memory is not initialized.
- If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().
- So, malloc() returns uninitialized memory, the contents of which is indeterminate.
if (arr[i] != 0)
- In your program, You have tried to access the content of a memory block, which is invoked undefined behavior.
Linux - Solution 3:
It is easy to see malloc doesn't zero initialize memory.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
{
double *a = malloc(sizeof(double)*100);
*a = 100;
printf("%f\n", *a);
free(a);
}
{
double *a = malloc(sizeof(double)*100);
printf("%f\n", *a);
free(a);
}
return 0;
}
click below button to copy the code. By - Linux tutorial - team
Output with gcc 4.3.4
100.000000
100.000000
Linux - Solution 4:
The standard does not dictate that malloc() should initialize the values to zero. It just happens at your platform that it might be set to zero, or it might have been zero at the specific moment you read that value.
Linux - Solution 5:
From gnu.org:
- Very large blocks (much larger than a page) are allocated with mmap (anonymous or via /dev/zero) by this implementation.