Expert C Programming

(Jeff_L) #1
free(p); p = NULL;

This ensures that if you do use a pointer after you have freed it, at least the program
core dumps at once.


  1. Overwriting errors: writing past either end of an array, writing past either end of a
    malloc'd block, or overwriting some of the heap management structures (this is all too
    easy to do by writing before the beginning of a malloc'd block).


  2. p=malloc(256); p[-1]=0; p[256]=0;



  3. Free'ing errors: freeing the same block twice, freeing something that you didn't
    malloc, freeing some memory that is still in use, or freeing an invalid pointer. A very
    common free error is to cdr [3] down a linked list in a for (p=start; p; p=p-

    next) loop, then in the loop body do a free(p). This leads a freed pointer to be
    dereferenced on the next loop iteration, with unpredictable results.





[3] Car and cdr are two LISP terms for the head and remainder of a list, respectively.

Cdr'ing down a list is processing the list by picking successive elements off the front.
Car and cdr come from the IBM 704, a 36-bit vacuum-tube processor with 15-bit
addresses. Core memory locations were called "registers". CAR meant "contents of
address part of register", and CDR was "contents of decrement part of register". These
were brief routines, and the LISP 1.5 manual (MIT Press, 1962) lists them in their
entirety. Here's CAR

CAR SXA CARX,4
PDX 0,4
CLA 0,4
PAX 0,4
PXD 0,4
CARX AXT **,4
TRA 1,4

LISP 1.0 originally had CTR and CXR, too, contents of tag part of register and contents
of index part of register. These weren't very useful, and were dropped from LISP 1.5.

Handy Heuristic

Free download pdf