home *** CD-ROM | disk | FTP | other *** search
/ Monster Media 1994 #1 / monster.zip / monster / PROG_C / SNPD9404.ZIP / MEM.TXT < prev    next >
Text File  |  1994-04-03  |  9KB  |  216 lines

  1.                         Walter Bright's MEM Package
  2.                         ---------------------------
  3.  
  4.  
  5. PREFACE:
  6. --------
  7.  
  8. The files, MEM.H and MEM.C which constitute the MEM package were originally
  9. published in the March-April 1990 edition of Micro Cornucopia magazine, now
  10. sadly out of print.  The files as they appear in SNIPPETS have been edited
  11. somewhat to remove compiler dependencies and correct minor discrepancies.
  12.  
  13. For those who don't already know, Walter Bright is the author of Datalight
  14. Optimum-C, the original optimizing C compiler for PC's.  Through a succession
  15. of sales and acquisitions plus continual improvement by Walter,, his compiler
  16. became Zortech C++ and is now sold as Symantec C++.  As such, it is the only
  17. major PC compiler which can claim single authorship.  It also compiles faster
  18. than most other compilers and is still a market leader in its optimization
  19. technology.
  20.  
  21. Like many other library and ancillary functions unique to Walter's compilers,
  22. the MEM package was originally something he wrote for his own use.  As noted
  23. above, he published it only once but it has been included as an unheralded
  24. "freebie" in Walter's compilers for the past several years.  Walter was kind
  25. enough to grant permission for its inclusion in SNIPPETS beginning with the
  26. April, '94 release.
  27.  
  28.  
  29. WHAT IS MEM?:
  30. -------------
  31.  
  32. MEM is a set of functions used for debugging C pointers and memory allocation
  33. problems.  Quoting Walter, "Symptoms of pointer bugs include: hung machines,
  34. scrambled disks, failures that occur once-in-10,000 iterations, irreprodu-
  35. cible results, and male pattern baldness." After writing MEM for use in
  36. developing his own compiler and tools, he reported that its use reduced
  37. pointer bugs by as much as 75%.  MEM is simple to add to existing programs
  38. and adds little or no overhead.
  39.  
  40.  
  41. USING MEM:
  42. ----------
  43.  
  44. Included in the MEM package is TOOLKIT.H, which isolates compiler and
  45. environmental dependencies.  It should work as-is for most PC compilers and
  46. the Microsoft compiler for SCO Unix.  Other environments may be customized by
  47. writing your own HOST.H file, using the existing definitions in TOOLKIT.H as
  48. examples and modifying the values to match your system.  Using these
  49. techniques, the MEM package has been used successfully on Amigas, Macs,
  50. VAXes, and many other non-DOS systems.
  51.  
  52. The MEM functions exactly parallel the standard library (plus 1 non-standard)
  53. memory allocation functions.  To implement MEM in your program, simply do a
  54. global search-and-replace of the following functions:
  55.  
  56.       malloc()    ->    mem_malloc()
  57.       calloc()    ->    mem_calloc()
  58.       realloc()   ->    mem_realloc()
  59.       free()      ->    mem_free()
  60.       strdup()    ->    mem_strdup()
  61.  
  62. At the beginning of main(), add the following lines:
  63.  
  64.       mem_init();
  65.       atexit(mem_term);
  66.  
  67. In the header section of each of your C files, add...
  68.  
  69. #include "mem.h"
  70.  
  71. ...to every .C file which calls any of the above functions.
  72.  
  73. The final step is to compile and link MEM.C into all programs using the MEM
  74. package.  It really is a pretty simple procedure!
  75.  
  76. MEM has 2 modes of operation, debugging and non-debugging.  Use debugging
  77. mode during program development and then turn debugging off for final
  78. production code.  Control of debugging is by defining the MEM_DEBUG macro.
  79. If the macro is defined, debugging is on; if undefined, debugging is off.
  80. The default is non-debugging, in which case the MEM functions become trivial
  81. wrappers for the standard functions, incurring virtually no overhead.
  82.  
  83.  
  84. WHAT MEM DOES:
  85. --------------
  86.  
  87. 1.    ISO/ANSI verification:
  88.  
  89. When Walter wrote MEM, compiler compliance with ANSI standards was still
  90. quite low.  MEM verifies ISO/ANSI compliance for situations such as passing
  91. NULL or size 0 to allocation/reallocation functions.
  92.  
  93. 2.    Logging of all allocations and frees:
  94.  
  95. All MEM's functions pass the __FILE__ and __LINE__ arguments.  During alloca-
  96. tion, MEM makes an entry into a linked list and stores the file and line
  97. information in the list for whichever allocation or free function is called.
  98.  
  99. This linked list is the backbone of MEM.  When MEM detects a bug, it tells
  100. you where to look in which file to begin tracking the problem.
  101.  
  102. 3.    Verification of frees:
  103.  
  104. Since MEM knows about all allocations, when a pointer is freed, MEM can
  105. verify that the pointer was allocated originally.  Additionally, MEM will
  106. only allow a pointer to be freed once.
  107.  
  108. Freed data is overwritten with a non-zero known value, flushing such problems
  109. as continuing to reference data after it's been freed.  The value written
  110. over the data is selected to maximize the probability of a segment fault or
  111. assertion failure if your application references it after it's been freed.
  112.  
  113. MEM obviously can't directly detect "if" instances such as...
  114.  
  115.       mem_free(p);
  116.       if (p) ...
  117.  
  118. ...but by guaranteeing that `p' points to garbage after being freed, code
  119. like this will hopefully never work and will thus be easier to find.
  120.  
  121. 4.    Detection of pointer over- and under-run:
  122.  
  123. Pointer overrun occurs when a program stores data past the end of a buffer,
  124. e.g.
  125.  
  126.       p = malloc(strlen(s));        /* No space for terminating NUL      */
  127.       strcpy(p,s);                  /* Terminating NUL clobber memory   */
  128.  
  129. Pointer underrun occurs when a program stores data before the beginning of a
  130. buffer.  This error occurs less often than overruns, but MEM detects it
  131. anyway.  MEM does this by allocating a little extra at each end of every
  132. buffer, which is filled with a known value, called a sentinel. MEM detects
  133. overruns and underruns by verifying the sentinel value when the buffer is
  134. freed.
  135.  
  136. 5.    Dependence on values in buffer obtained from malloc():
  137.  
  138. When obtaining a buffer from malloc(), a program may develop erroneous and
  139. creeping dependencies on whatever random (and sometimes repeatable) values
  140. the buffer may contain.  The mem_malloc() function prevents this by always
  141. setting the data in a buffer to a known non-zero value before returning its
  142. pointer.  This also prevents another common error when running under MS-DOS
  143. which doesn't clear unused memory when loading a program.  These bugs are
  144. particularly nasty to find since correct program operation may depend on what
  145. was last run!
  146.  
  147. 6.    Realloc problems:
  148.  
  149. Common problems when using realloc() are: 1) depending on realloc() *not*
  150. shifting the location of the buffer in memory, and 2) depending on finding
  151. certain values in the uninitialized region of the realloc'ed buffer.
  152.  
  153. MEM flushes these out by *always* moving the buffer and stomping on values
  154. past the initialized area.
  155.  
  156. 7.    Memory leak detection:
  157.  
  158. Memory "leaks" are areas that are allocated but never freed.  This can become
  159. a major problem in programs that must run for long periods without interrup-
  160. tion (e.g. BBS's).  If there are leaks, eventually the program will run out
  161. of memory and fail.
  162.  
  163. Another form of memory leak occurs when a piece of allocated memory should
  164. have been added to some central data structure, but wasn't.
  165.  
  166. MEM find memory leaks by keeping track of all allocations and frees.  When
  167. mem_term() is called, a list of all unfreed allocations is printed along with
  168. the files and line numbers where the allocations occurred.
  169.  
  170. 8.    Pointer checking:
  171.  
  172. Sometimes it's useful to be able to verify that a pointer is actually
  173. pointing into free store. MEM provides a function...
  174.  
  175.       mem_checkptr(void *p);
  176.  
  177. ...to do this.
  178.  
  179. 9.    Consistency checking:
  180.  
  181. Occasionally, even MEM's internal data structures get clobbered by a wild
  182. pointer.  When this happens, you can track it down by sprinkling your code
  183. temporarily with calls to mem_check(), which performs a consistency check on
  184. the free store.
  185.  
  186. 10.   Out of memory handling:
  187.  
  188. MEM can be set using mem_setexception() (see MEM.H) to handle out-of-memory
  189. conditions in any one of several predefined ways:
  190.  
  191.       1.    Present an "Out of memory" message and terminate the program.
  192.       2.    Abort the program with no message.
  193.       3.    Mimic ISO/ANSI and return NULL.
  194.       4.    Call a user-specified function, perhaps involving virtual memory
  195.             or some other "emergency reserve".
  196.       5.    Retry (be careful to avoid infinite loops!)
  197.  
  198. 11.   Companion techniques:
  199.  
  200. Since MEM presets allocated and stomps on freed memory, this facilitates
  201. adding your own code to add tags to your data structures when debugging.  If
  202. the structures are invalid, you'll know it because MEM will have clobbered
  203. your verification tags.
  204.  
  205.  
  206. SUMMARY:
  207. --------
  208.  
  209. Since it is, in the final analysis, a software solution, MEM is fallible.  As
  210. the saying goes, "Nothing is foolproof because fools are so ingenious."
  211. Walter himself readily acknowledges that there are circumstances where your
  212. code can do sufficient damage to MEM's internal data structures to render it
  213. useless.  The good news is such circumstances are few and far between.  For
  214. most memory debugging, MEM is a highly reliable and valuable addition to your
  215. C programming toolchest.
  216.