ebmDevMag.com home
ebm Developer's Magazine
links

developer's mag
main page

article
part 1
part 2
part 3
part 4
part 5
part 6
part 7
part 8


6 - Adding Protection

With the extra data in hand, we can monitor the memory better, specifically:

  • We add guard bytes at the end, to detect overwrites (past end of valid memory).
  • Guard bytes at the front (before the pointer value returned by malloc), do the same for underwriting.
  • Pointer information allows us to walk our memory list, checking for valid blocks, monitoring the integrity, and checking for blocks not freed by the time the program ends.
  • Each block contains source information, identifying its creation by source code file and line number, to help in tracking (a maximum of 15 characters of the file name are stored).
  • The block allocated size is stored, allowing us to figure out if a pointer access will overrun.

The steps to use are simple:

  1. Add pa_mem.cpp to your makefile and source directory
  2. Include the memory routines in your code with #include "pa_mem.h"
  3. Sweep your code, changing malloc, free, calloc and realloc to the following:
    malloc becomes MEM_MALLOC
    calloc becomes MEM_CALLOC
    realloc becomes MEM_REALLOC
    free becomes MEM_FREE

You'll also need assert2.cpp included in your project, since the code depends on the NDEBUG flag to compile. If not set, you get ASSERTING() and memory testing; if NDEBUG is defined, these are both turned off, and the result with the memory calls is that they compile to the original allocation function calls (malloc() etc), with no loss of speed or flexibility.

Previous Section
Next Section

Copyright © 2001-2006 ebmDevMag.com - Legal Notice