title: What is the difference between glibc's MALLOC_CHECK_, M_CHECK_ACTION, and mcheck?
body: <p>glibc seems to have more than one way of doing some heap checking:</p>
  
  <ol>
  <li>mallopt with the M_CHECK_ACTION parameter</li>
  <li>the MALLOC_CHECK_ environment variable</li>
  <li>the mcheck family of functions</li>
  </ol>
  
  <p>I find the available documentation to be confusing.  The <a href="http://www.gnu.org/software/libc/manual/html_node/Malloc-Tunable-Parameters.html" rel="noreferrer">manual</a> doesn't list M_CHECK_ACTION at all when describing mallopt.  <a href="http://man7.org/linux/man-pages/man3/mallopt.3.html" rel="noreferrer">This mallopt man page</a>, however, <em>does</em> describe M_CHECK_ACTION.  Additionally, it says it's equivalent to the environment variable MALLOC_CHECK_:</p>
  
  <blockquote>
  <pre><code>   MALLOC_CHECK_
            This environment variable controls the same parameter as
            mallopt() M_CHECK_ACTION.  If this variable is set to a
            nonzero value, then a special implementation of the memory-
            allocation functions is used.  (This is accomplished using the
            malloc_hook(3) feature.)  This implementation performs
            additional error checking, but is slower than the standard set
            of memory-allocation functions.
  </code></pre>
  </blockquote>
  
  <p>The glibc manual has a page for <a href="http://www.gnu.org/software/libc/manual/html_node/Heap-Consistency-Checking.html" rel="noreferrer">mcheck and friends</a> and describes them as "heap consistency checking".  It is on this page that the manual discusses MALLOC_CHECK_:</p>
  
  <blockquote>
    <p>Another possibility to check for and guard against bugs in the use of malloc, realloc and free is to set the environment variable MALLOC_CHECK_. When MALLOC_CHECK_ is set, a special (less efficient) implementation is used which is designed to be tolerant against simple errors, such as double calls of free with the same argument, or overruns of a single byte (off-by-one bugs). </p>
  </blockquote>
  
  <p>So mcheck et al is an alternative to MALLOC_CHECK_/M_CHECK_ACTION?</p>
  
  <p>Furthermore, how does one disable all this super-helpful consistency checking?  The man page says setting MALLOC_CHECK_ (and therefore M_CHECK_ACTION) to 0 will not use "a special implementation of the memory-allocation functions."  The glibc manual, however, states that "When MALLOC_CHECK_ is set, a special (less efficient) implementation is used."  An environment variable set to 0 is still set, so one of these is wrong.</p>
  
  <p>My own experiments (using the example program from <a href="http://man7.org/linux/man-pages/man3/mcheck.3.html" rel="noreferrer">this mcheck man page</a>) show that not having MALLOC_CHECK_ set at all results in the same behavior as MALLOC_CHECK_=3 (on RHEL 6.4).  And mcheck seems completely unrelated, as it can be set independently.</p>