In what circumstances can malloc_trim(0) cause a crash?

320 views Asked by At

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.

1

There are 1 answers

0
chqrlie On

Here is the man page for malloc_trim():

MALLOC_TRIM(3)                 Linux Programmer's Manual               MALLOC_TRIM(3)

NAME

malloc_trim - release free memory from the top of the heap

SYNOPSIS

#include <malloc.h>

int malloc_trim(size_t pad);

DESCRIPTION

The malloc_trim() function attempts to release free memory at the top of the heap (by calling sbrk(2) with a suitable argument).

The pad argument specifies the amount of free space to leave untrimmed at the top of the heap. If this argument is 0, only the minimum amount of memory is maintained at the top of the heap (i.e., one page or less). A nonzero argument can be used to maintain some trailing space at the top of the heap in order to allow future allocation to be made without having to extend the heap with sbrk(2).

RETURN VALUE

The malloc_trim() function returns 1 if memory was actually released back to the system, or 0 if it was not possible to release any memory.

ERRORS

No errors are defined.

CONFORMING TO

This function is a GNU extension.

NOTES

This function is automatically called by free(3) in certain circumstances; see the discussion of M_TOP_PAD and M_TRIM_THRESHOLD in mallopt(3).

This function cannot release free memory located at places other than the top of the heap.

This function releases only memory in the main arena.

0 is 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 calling malloc_trim(). These errors could be:

  • modification of bytes beyond the end or before the beginning of an allocated block
  • modification of a block after it has been freed
  • multiple frees of the same block

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 with sbrk(). Modern allocators use mmap to allocate different arenas and should handle the release of unused pages back to the OS automatically.