does malloc cause swapping out?

Kevin Buettner plug-devel@lists.PLUG.phoenix.az.us
Fri Apr 12 16:50:01 2002


On Apr 12,  2:16pm, Monika wrote:

> I would like to know if malloc can cause pages to be swapped out.

Not directly.  I.e, if you look at the malloc() implementation in
glibc, you won't find any code responsible for swapping pages out.
Swapping pages is the kernel's responsibility.

> Here's an extended version of my question:
> 
> This is what I was able to find out and what hopefully is correct:
> 
> Each process gets a chunk of memory to manage at the beginning of its
> execution. There is a code segment, heap space that grows "upwards" and stack
> that grows "downwards". A space between a stack and a heap is sort of a
> no-man's land that gets allocated with mmap as the executions progresses.

You should also know that the "bottom" of the stack won't necessarily
be at the highest address.  Depending upon the architecture (or upon
how imaginative your linker scripts are), it may be possible to mmap
pages above the stack as well.

> Malloc can raise up the heap and it is implemented by a syscall brk.
> If brk wants to raise the end of the heap, but there is no free space,
> because there is something in there that was allocated with mmap, then
> brk returns an old address of the end of the heap.

That's how things were traditionally done.  If you strace a small program
which uses malloc() though, I think you'll find that mmap() is used to
allocate pages for the malloc() arenas.

> Now here's where my confusion starts. I did a little bit of function tracing
> (on 2.2.x kernel) and noticed that kmalloc can eventaully cause pages to be
> swapped out (if the region immediatelly above the heap is allocated and we
> need to increase the heap space). 

Right.  That's in the kernel.  malloc() is a user space function.

> I wanted to check if malloc() can eventually cause pages to be swapped out
> similarly to what kernel malloc (kmalloc) can do.

As I noted above, not directly.  The way it'll (roughly) work is that
the kernel will get a memory allocation request (perhaps via the mmap
syscall.  If it can't find enough memory to fulfill that request, it
may eventually cause some paging activity.

Kevin