Why does malloc initialize the values to 0 in gcc?

前端 未结 9 1969
慢半拍i
慢半拍i 2020-11-22 16:34

Maybe it is different from platform to platform, but

when I compile using gcc and run the code below, I get 0 every time in my ubuntu 11.10.

#include         


        
9条回答
  •  一生所求
    2020-11-22 16:38

    Why do you assume that malloc() initializes to zero? It just so happens to be that the first call to malloc() results in a call to sbrk or mmap system calls, which allocate a page of memory from the OS. The OS is obliged to provide zero-initialized memory for security reasons (otherwise, data from other processes gets visible!). So you might think there - the OS wastes time zeroing the page. But no! In Linux, there is a special system-wide singleton page called the 'zero page' and that page will get mapped as Copy-On-Write, which means that only when you actually write on that page, the OS will allocate another page and initialize it. So I hope this answers your question regarding performance. The memory paging model allows usage of memory to be sort-of lazy by supporting the capability of multiple mapping of the same page plus the ability to handle the case when the first write occurs.

    If you call free(), the glibc allocator will return the region to its free lists, and when malloc() is called again, you might get that same region, but dirty with the previous data. Eventually, free() might return the memory to the OS by calling system calls again.

    Notice that the glibc man page on malloc() strictly says that the memory is not cleared, so by the "contract" on the API, you cannot assume that it does get cleared. Here's the original excerpt:

    malloc() allocates size bytes and returns a pointer to the allocated memory.
    The memory is not cleared. If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

    If you would like, you can read more about of that documentation if you are worried about performance or other side-effects.

提交回复
热议问题