This is the mail archive of the libc-alpha@sourceware.org mailing list for the glibc project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

malloc: madvise(MADV_DONTNEED) upon implicit trim as well as explicit?


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


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]