unitialized memory is all zeros...why not garbage instead?

Steve Watt steve at Watt.COM
Mon Jun 13 19:49:01 GMT 2005


Mike Hunter <mhunter at ack.berkeley.edu> wrote:
>On Jun 11, "Dag-Erling Smrgrav" wrote:
>> Mike Hunter <mhunter at ack.berkeley.edu> writes:
>> > I have a feeling that I'm missing something really obvious, but I'm having
>> > trouble understanding why the following program:
>> > [...]
>> > Never prints anything but "0"'s.
>> 
>> Because the kernel always hands processes pre-zeroed pages.
>
>Thanks for setting me straight.  I guess it wasn't this way on DOS where I
>first learned C++ and I've assumed garbage ever since :)
>
>Is the pre-zeroing of malloc'd memory documented somewhere?  By my reading 
>of the malloc manapge...

Careful now:  The return value in memory from malloc() is not directly
related to the return value in memory from sbrk().  malloc() may give
the application back memory that was free()d previously by the same
application.  New pages that come out of sbrk() are 0s, but those aren't
always needed to fulfill a malloc() request.

>     The calloc() function allocates space for number objects, each size 
>     bytes in length.  The result is identical to calling malloc() with an
>     argument of ``number * size'', with the exception that the allocated 
>     memory is explicitly initialized to zero bytes.
>
>...it seems like it's saying that malloc (as opposed to calloc) is NOT
>pre-zeroed.  Is there a different document I should be reading?

And if calloc() grabs something from the in-process "used, now free" pool, it
will be zeroed.  If malloc() grabs something from that same pool, it won't
be.

-- 
Steve Watt KD6GGD  PP-ASEL-IA          ICBM: 121W 56' 57.8" / 37N 20' 14.9"
 Internet: steve @ Watt.COM                         Whois: SW32
   Free time?  There's no such thing.  It just comes in varying prices...


More information about the freebsd-hackers mailing list