Go to the first, previous, next, last section, table of contents.


Heap Consistency Checking

You can ask malloc to check the consistency of dynamic storage by using the mcheck function. This function is a GNU extension, declared in `malloc.h'.

Function: int mcheck (void (*abortfn) (enum mcheck_status status))
Calling mcheck tells malloc to perform occasional consistency checks. These will catch things such as writing past the end of a block that was allocated with malloc.

The abortfn argument is the function to call when an inconsistency is found. If you supply a null pointer, then mcheck uses a default function which prints a message and calls abort (see section Aborting a Program). The function you supply is called with one argument, which says what sort of inconsistency was detected; its type is described below.

It is too late to begin allocation checking once you have allocated anything with malloc. So mcheck does nothing in that case. The function returns -1 if you call it too late, and 0 otherwise (when it is successful).

The easiest way to arrange to call mcheck early enough is to use the option `-lmcheck' when you link your program; then you don't need to modify your program source at all.

Function: enum mcheck_status mprobe (void *pointer)
The mprobe function lets you explicitly check for inconsistencies in a particular allocated block. You must have already called mcheck at the beginning of the program, to do its occasional checks; calling mprobe requests an additional consistency check to be done at the time of the call.

The argument pointer must be a pointer returned by malloc or realloc. mprobe returns a value that says what inconsistency, if any, was found. The values are described below.

Data Type: enum mcheck_status
This enumerated type describes what kind of inconsistency was detected in an allocated block, if any. Here are the possible values:

MCHECK_DISABLED
mcheck was not called before the first allocation. No consistency checking can be done.
MCHECK_OK
No inconsistency detected.
MCHECK_HEAD
The data immediately before the block was modified. This commonly happens when an array index or pointer is decremented too far.
MCHECK_TAIL
The data immediately after the block was modified. This commonly happens when an array index or pointer is incremented too far.
MCHECK_FREE
The block was already freed.


Go to the first, previous, next, last section, table of contents.