A useful feature: instead of programmatically using the mallopt(3) API, the system allows us to tune some allocation parameters conveniently via environment variables. Most useful, perhaps, from the viewpoint of debug and testing, the MALLOC_CHECK_ variable is the environment variable corresponding to the M_CHECK_ACTION parameter described earlier; thus, we can just set the value, run our application, and see the result for ourselves!
A few examples follow, using our usual membugs application to check out some test cases:
Test case # 10: double free with MALLOC_CHECK_ set:
$ MALLOC_CHECK_=1 ./membugs_dbg 10
doublefree(): cond 0
doublefree(): cond 1
membugs.c:doublefree:134: malloc failed
*** Error in `./membugs_dbg': free(): invalid pointer: 0x00005565f9f6b420 ***
$ MALLOC_CHECK_=3 ./membugs_dbg 10
doublefree(): cond 0
doublefree(): cond 1
membugs.c:doublefree:134: malloc failed
*** Error in `./membugs_dbg': free(): invalid pointer: 0x0000562f5da95420 ***
Aborted
$ MALLOC_CHECK_=5 ./membugs_dbg 10
doublefree(): cond 0
doublefree(): cond 1
membugs.c:doublefree:134: malloc failed
$ MALLOC_CHECK_=7 ./membugs_dbg 10
doublefree(): cond 0
doublefree(): cond 1
membugs.c:doublefree:134: malloc failed
$
Notice how, with the value of MALLOC_CHECK_ being 1, the error message, is printed but the process is not aborted; this is what happens when the value of the environment variable is set to 3.
Test case # 7: out-of-bounds (read underflow) with MALLOC_CHECK_ set:
$ MALLOC_CHECK_=3 ./membugs_dbg 7
read_underflow(): cond 0
dest: abcd56789
read_underflow(): cond 1
dest: xabcd56789
*** Error in `./membugs_dbg': free(): invalid pointer: 0x0000562ce36d9420 ***
Aborted
$
Test case # 11: memory leak test case 1—simple leak with MALLOC_CHECK_ set:
$ MALLOC_CHECK_=3 ./membugs_dbg 11
leakage_case1(): will now leak 32 bytes (0 MB)
leakage_case1(): will now leak 1048576 bytes (1 MB)
$
Notice how a leakage bug test case is not detected.