I have a piece of code where I am using malloc_trim(0) to release any unused memory back to the system.
But very intermittently I am see that it causes a crash. Backtraces below:
Program terminated with signal SIGSEGV, Segmentation fault.
#0 mtrim (pad=0, av=0xffff8eebf9f8 <main_arena>) at malloc.c:4771
4771 INTERNAL_SIZE_T size = chunksize (p);
#0 mtrim (pad=0, av=0xffff8eebf9f8 <main_arena>) at malloc.c:4771
#1 __malloc_trim (s=s@entry=0) at malloc.c:4822
I would like to know the reason for this crash and how to avoid it.
I checked the man page for malloc_trim(), it does not look like it can cause a crash.
Here is the man page for
malloc_trim():0is a perfectly fine argument for this GNU extended function. The errors reported seem to indicate a corruption of the heap, possibly caused by your program before callingmalloc_trim(). These errors could be:You should investigate with memory tools such as valgrind to identify these problems.
Also note that
malloc_trim()is not portable and of limited interest in practice as it only trims the legacy heap allocated withsbrk(). Modern allocators usemmapto allocate different arenas and should handle the release of unused pages back to the OS automatically.