Skip site navigation (1)Skip section navigation (2)
Date:      Thu, 22 Aug 2002 22:11:12 -0700
From:      David Schultz <dschultz@uclink.Berkeley.EDU>
To:        "Un, SungKyong" <skun@etri.re.kr>
Cc:        freebsd-hackers@FreeBSD.ORG
Subject:   Re: userland malloc() and zeroed page allocation in Kernel
Message-ID:  <20020823051112.GB2687@HAL9000.homeunix.com>
In-Reply-To: <001601c24a4a$121fbb60$1bf2fe81@etri.re.kr>
References:  <001601c24a4a$121fbb60$1bf2fe81@etri.re.kr>

next in thread | previous in thread | raw e-mail | index | archive | help
Thus spake Un, SungKyong <skun@etri.re.kr>:
>     for (i=0; i<200;i++) {
>         malloc(1MB);
>         check it's all zeroed;
>         set this block to 'X';
>     }
>     free all allocated memory(200MB);
>     for (i=0; i<200;i++) {
>         malloc(1MB);
>         check it's all 'X';
>     }
> 
> The first for loop shows that 200 1MB blocks are all zeroed. The second for
> loop shows that
> only the first 1MB has 'X' value and rest blocks are all zeroed.

For efficiency reasons, phkmalloc doesn't actually release freed
memory back to the system in the way you might expect, at least
not most of the time.  Instead, it advises the kernel that the
physical pages do not contain important data and may be reused if
necessary.  If the system reclaims the pages for another process,
the original process gets brand new zeroed pages if it needs them
later on.  But if the memory load is low enough that the system
does not need to reclaim the pages, the process just reuses the
same pages, and the kernel saves the effort of having to fault in
new zeroed pages.

In your example above, the system reused most of the allocated
pages after they were freed, but was able to salvage a few of them
and save itself the trouble when you reused them.  Take a look at
MADV_FREE in the madvise(2) manpage.

In any case, you should never depend on memory allocated with
malloc() being zeroed, not even the first time you make an
allocation.  If you really want it to be zero, you have to use an
interface like calloc() that does this for you or explicitly zero
it yourself.

To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-hackers" in the body of the message




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