This is the mail archive of the
libc-alpha@sourceware.org
mailing list for the glibc project.
malloc: madvise(MADV_DONTNEED) upon implicit trim as well as explicit?
- From: Zack Weinberg <zackw at panix dot com>
- To: GNU C Library <libc-alpha at sourceware dot org>, DJ Delorie <dj at redhat dot com>
- Date: Thu, 28 Jul 2016 15:33:35 -0400
- Subject: malloc: madvise(MADV_DONTNEED) upon implicit trim as well as explicit?
- Authentication-results: sourceware.org; auth=none
Consider the following test program (modified from
https://stackoverflow.com/questions/38644578):
#include <stdlib.h>
#include <malloc.h>
#define NUM_CHUNKS 1000000
#define CHUNK_SIZE 100
static void *array[NUM_CHUNKS];
int
main (void)
{
// disable fast bins
mallopt (M_MXFAST, 0);
malloc_stats ();
// allocate many small chunks
for (unsigned int i = 0; i < NUM_CHUNKS; i++)
{
array[i] = malloc (CHUNK_SIZE);
if (!array[i])
abort ();
}
malloc_stats ();
// release almost all chunks
for (unsigned int i = 0; i < NUM_CHUNKS - 1; i++)
free (array[i]);
malloc_stats ();
// explicit trim
malloc_trim (0);
malloc_stats ();
// release the last chunk
free (array[NUM_CHUNKS - 1]);
malloc_stats ();
return 0;
}
All of the chunks get allocated from the brk() arena, so, naturally,
not deallocating the last-allocated chunk means that the arena cannot
be shrunk, even though 99.99% of it is free space. However, an
explicit call to malloc_trim() also causes a call to
madvise(MADV_DONTNEED) for the region of memory that's no longer in
use, which means that physical RAM *is* released back to the operating
system. This does *not* happen for implicit trimming done by free().
[Concretely, free() and malloc_trim() both call systrim() to try to
use sbrk(-N), but malloc_trim does extra work, including this call to
madvise().]
I wonder if it would make sense to move the extra work done by
malloc_trim into systrim() so that programs that don't use malloc_trim
can still benefit from it.
zw