Next: , Previous: Example 4, Up: Examples

16.5 Checking memory accesses

For the ultimate in heap checking, if you are using the GNU compiler you can use the -fcheck-memory-usage option. This instructs the compiler to place error-checking calls before each read or write to memory. The functions that are called then check to ensure that the memory access does not overflow a heap memory allocation or access free memory.

The following test (which can be found in tests/fail/test17.c) has an example of a read from memory which overflows a memory allocation's boundaries.

     23  /*
     24   * Allocates a single byte of memory and then attempts to read the
     25   * byte as a word, resulting in some uninitialised bytes being read.
     26   * This can sometimes be detected with PAGEALLOC=UPPER but can always
     27   * be detected with OFLOWWATCH or by using the -fcheck-memory-usage
     28   * option of gcc.
     29   */
     32  #include "mpatrol.h"
     35  int main(void)
     36  {
     37      int *p;
     38      int r;
     40      if (p = (int *) calloc(1, 1))
     41      {
     42          r = p[0];
     43          free(p);
     44      }
     45      return EXIT_SUCCESS;
     46  }

For this example, the above test must be compiled with gcc with the -fcheck-memory-usage option on the compiler command line and linked with the mpatrol library. Normally, the test will pass and not cause any problems, since most malloc libraries will allocate at least one word anyway. However, there are some instances where that will not be the case, especially on systems where misaligned memory accesses are legal. Also, if the implementation of calloc() only initialised the number of bytes requested then the number read back might not be zero.

If you now run the program it should abort and produce something similar to the following in the resulting mpatrol.log.

     ERROR: [RNGOVF]: range [0x00022568,0x0002256B] overflows
         0x00022568 (1 byte) {calloc:19:0} [main|test17.c|40]
             0x00010A0C main+96
             0x0001087C _start+100

As you can see, the mpatrol library detected a read beyond the boundaries of the one byte memory allocation starting at `0x00022568'.