Specifying an error handler

Typically, when the library detects an error, a diagnostic message is printed and the program continues executing. In cases where the allocation chains or another crucial part of the allocator's view is hopelessly corrupted, an error message is printed and the program is aborted (via abort() ).

You can override this default behavior by specifying what to do when a warning or a fatal condition is detected:

cmd
The error handler to set; one of:
MALLOC_FATAL
Specify the malloc fatal handler. Environment variable: MALLOC_FATAL.
MALLOC_WARN
Specify the malloc warning handler handler. Environment variable: MALLOC_WARN.
value
An integer value that indicates which one of the standard handlers provided by the library to use:
M_HANDLE_ABORT
Terminate execution with a call to abort().
M_HANDLE_EXIT
Exit immediately.
M_HANDLE_IGNORE
Ignore the error and continue.
M_HANDLE_CORE
Cause the program to dump a core file.
M_HANDLE_SIGNAL
Stop the program when this error occurs, by sending it a stop signal (SIGSTOP). This lets you attach to this process using a debugger. The program is stopped inside the error-handler function, and a backtrace from there should show you the exact location of the error.

If you use environment variables to specify options to the malloc library for either MALLOC_FATAL or MALLOC_WARN, you must pass the value that indicates the handler, not its symbolic name:

Handler Value
M_HANDLE_IGNORE 0
M_HANDLE_ABORT 1
M_HANDLE_EXIT 2
M_HANDLE_CORE 3
M_HANDLE_SIGNAL 4

These values are also defined in /usr/include/malloc_g/malloc-lib.h.

You can OR any of these handlers with the value, MALLOC_DUMP, to cause a complete dump of the heap before the handler takes action.

Here's how you can cause a memory overrun error to abort your program:

...
int *foo, *p, i;
int opt;
opt = 1;
mallopt(MALLOC_FILLAREA,  opt);
foo = (int *)malloc(10*4);
for (p = foo, i = 12; i > 0; p++, i--)
    *p = 89;
opt = M_HANDLE_ABORT;
mallopt(MALLOC_WARN, opt);
free(foo); /* a fatal error is generated here */