iTranslated by AI
Solving glibc malloc memory fragmentation
When you temporarily allocate 20MB of memory, the first time it is returned to the OS immediately, and the RSS decreases. However, from the second time onwards, it may not decrease, causing the RSS to steadily increase due to fragmentation.
This is because glibc malloc allocates memory using mmap for the first time, but starts using brk for subsequent allocations.
The threshold for glibc malloc's mmap and brk starts at 128 * 1024 bytes, but it is dynamic by default.
# if __WORDSIZE == 32
# define DEFAULT_MMAP_THRESHOLD_MAX (512 * 1024)
# else
# define DEFAULT_MMAP_THRESHOLD_MAX (4 * 1024 * 1024 * sizeof(long))
# endif
#endif
In a 64-bit environment, sizeof(long) == 8, so the threshold can increase up to 32MB.
Let's verify this in practice.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
void malloc_and_free() {
// Allocate 20MB
const size_t size = 20 * 1024 * 1024;
puts("malloc");
void *p = malloc(size);
memset(p, 0, size);
sleep(5);
puts("free");
free(p);
sleep(5);
}
int main() {
malloc_and_free();
malloc_and_free();
malloc_and_free();
return 0;
}
$ gcc main.c
$ ./a.out
By checking at appropriate timings using:
$ ps u -p $(pgrep a.out)
You will observe that the RSS does not decrease after the second free. In a synchronous and simple case, this may not be a problem and might even be slightly faster, which is welcome. However, in asynchronous or multi-threaded scenarios, where arenas are separated and memory is not reused, it is undesirable to see the RSS simply inflate due to waste. Let's solve this by setting the mmap threshold.
$ MALLOC_MMAP_THRESHOLD_=131072 ./a.out
If memory fragmentation of about 10-30MB is causing the RSS to bloat, you can avoid it by setting the environment variable appropriately.
This approach might be preferable in some cases compared to using jemalloc or mimalloc, which consume significant memory from the start.
That's it.
Discussion