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:
- The error handler to set; one of:
- Specify the malloc fatal handler. Environment variable: MALLOC_FATAL.
- Specify the malloc warning handler handler. Environment variable: MALLOC_WARN.
- An integer value that indicates which one of the standard
handlers provided by the library to use:
- Terminate execution with a call to abort().
- Exit immediately.
- Ignore the error and continue.
- Cause the program to dump a core file.
- 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:
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 */