Specifying an error handler

Typically, when the library detects an error, it displays a diagnostic message, 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 using the librcheck version of mallopt() to specify what to do when a warning or a fatal condition is detected:

cmd
The error handler to set; one of:
MALLOC_FATAL
Specify how to handle fatal errors.
MALLOC_WARN
Specify how to handle warnings.

Environment variable: MALLOC_ACTION, which sets the handling for fatal errors and warnings to the same value.

value
An integer value that indicates how you want to handle the error:
Symbolic name Value Action
M_HANDLE_IGNORE 0 Ignore the error and continue
M_HANDLE_ABORT 1 Terminate execution with a call to abort()
M_HANDLE_EXIT 2 Exit immediately
M_HANDLE_CORE 3 Cause the program to dump a core file
M_HANDLE_STOP 4 Send a stop signal (SIGSTOP) to the current thread. 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 call mallopt(), you can OR any of these handlers with M_HANDLE_DUMP, to cause a complete dump of the heap before the handler takes action.

If you use the environment variable, you must set it to one of the numeric values, not the corresponding M_HANDLE_* symbolic name.

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

...
int *foo, *p, i;
int opt;

opt = 1;
mallopt(MALLOC_CKBOUNDS,  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 */