jemalloc is hoarding memory
Author: jengelhCreated Mar 18, 2026Updated Mar 30, 2026
Version: jemalloc 5.3.0 linux-amd64 [openSUSE Tumbleweed 20260316]
A program that makes a lot (millions) of small allocations and then frees them makes jemalloc retain all those small buckets for itself rather than returning them to the OS. This issue was originally reported as https://sourceware.org/bugzilla/show_bug.cgi?id=33886 for glibc, but jemalloc is just affected the same.
Input code:
#include <stdlib.h>
#include <malloc.h>
size_t allocsize = 120;
void *one_thread(void *)
{
static const unsigned int nelem = 50000000;
char **arr = malloc(sizeof(char *) * nelem);
for (size_t i = 0; i < nelem; ++i)
arr[i] = malloc(allocsize);
for (size_t i = 0; i < nelem; ++i)
free(arr[i]);
free(arr);
return 0;
}
int main(int argc, char **argv)
{
allocsize = argc >= 2 ? strtoul(argv[1],nullptr,0) : 120;
system("ps u");
one_thread(0);
malloc_stats();
// about 217 MB retained
system("ps u");
return 0;
}Observed:
10:08 a4:~/work/gromox $ LD_PRELOAD=/usr/lib64/libjemalloc.so.2 ./a.out
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
ej 20911 0.0 0.0 14904 8664 pts/3 S+ 10:08 0:00 ./a.out
[…]
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
ej 20911 97.4 0.1 7493176 217784 pts/3 S+ 10:08 0:01 ./a.outExpected to see instead:
Since my million blocks account for almost all allocations the program ever makes, I would expect fragmentation after free() to be low and the 217 MB number reported by ps to significantly go down.
first ps:
ej 20911 x% x% 14904 8664 pts/3 S+ 10:08 0:00 ./a.out
second ps:
ej 20911 x% x% 16000 10000 pts/3 S+ 10:08 0:01 ./a.outSource: jemalloc/jemalloc