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.
- 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.
Output with gcc 4.3.4
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.