In multi-user operating systems, when memory is given to a process by the operating system, the operating system will typically clear the memory so that it does not reveal data that was previously there from other processes. (Of course, the system does not have to zero this memory; to protect privacy, it merely has to set the memory to any values that do not contain private data. Zero is usually used.)
This implies that when malloc
returns memory that is freshly obtained from the operating system, which of course happens when the pool of memory malloc
had previously is insufficient to satisfy your request, that memory will contain zeros. However, when malloc
returns memory that was previously used by your process, it may contain other data. (Some of this data may be from parts of your program that are not normally visible to you, such as the C run-time initialization code or dynamic loaders and linkers.)
Since this behavior is a result of your operating system and not of the C specification, you may not rely on it when basing software only on the C specification. When you do not have assurance that this behavior will occur, you must write software as if every malloc
could return uninitialized data, even if experience or examinations often show otherwise.