Skip site navigation (1)Skip section navigation (2)
Date:      Mon, 13 Jun 2005 12:48:59 -0700
From:      steve@Watt.COM (Steve Watt)
To:        mhunter@ack.berkeley.edu
Cc:        freebsd-hackers@freebsd.org
Subject:   Re: unitialized memory is all zeros...why not garbage instead?
Message-ID:  <200506131948.j5DJmx4e011440@wattres.watt.com>
In-Reply-To: <20050613193150.GA75218@malcolm.berkeley.edu>
References:  <20050610224058.GA11336@malcolm.berkeley.edu> <86vf4lb110.fsf@xps.des.no>

next in thread | previous in thread | raw e-mail | index | archive | help
Mike Hunter <mhunter@ack.berkeley.edu> wrote:
>On Jun 11, "Dag-Erling Smrgrav" wrote:
>> Mike Hunter <mhunter@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...



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?200506131948.j5DJmx4e011440>