#include <mcheck.h> int mcheck(void (*abortfunc)(enum mcheck_status mstatus));int mcheck_pedantic(void (*abortfunc)(enum mcheck_status mstatus));void mcheck_check_all(void);enum mcheck_status mprobe(void *ptr);
To be effective, the mcheck() function must be called before the first call to malloc(3) or a related function. In cases where this is difficult to ensure, linking the program with -lmcheck inserts an implicit call to mcheck() (with a NULL argument) before the first call to a memory-allocation function.
The mcheck_pedantic() function is similar to mcheck(), but performs checks on all allocated blocks whenever one of the memory-allocation functions is called. This can be very slow!
The mcheck_check_all() function causes an immediate check on all allocated blocks. This call is effective only if mcheck() is called beforehand.
If the system detects an inconsistency in the heap, the caller-supplied function pointed to by abortfunc is invoked with a single argument argument, mstatus, that indicates what type of inconsistency was detected. If abortfunc is NULL, a default function prints an error message on stderr and calls abort(3) .
The mprobe() function performs a consistency check on the block of allocated memory pointed to by ptr. The mcheck() function should be called beforehand (otherwise mprobe() returns MCHECK_DISABLED).
The following list describes the values returned by mprobe() or passed as the mstatus argument when abortfunc is invoked:
$ ./a.outAbout to free About to free a second time block freed twice Aborted (core dumped)
#include <stdlib.h> #include <stdio.h> #include <mcheck.h> int main(int argc, char *argv[]) { char *p; if (mcheck(NULL) != 0) { fprintf(stderr, "mcheck() failed\n"); exit(EXIT_FAILURE); } p = malloc(1000); fprintf(stderr, "About to free\n"); free(p); fprintf(stderr, "\nAbout to free a second time\n"); free(p); exit(EXIT_SUCCESS); }