Expert C Programming

(Jeff_L) #1

How to Free Elements in a Linked List


The correct way to free an element while traversing down a linked list is to use a temporary
variable to store the address of the next element. Then you can safely free the current
element at any time, and not have to worry about referencing it again to get the address of
the next. The code is:


struct node p, start, *tmp;


for (p=start; p; p=tmp) {


tmp=p->next;


free(p);


}


Software Dogma


Is Your Program Out of Space?


If your program needs more memory than the operating system can give it, it will be
terminated with a "segmentation fault". You can distinguish this type of segmentation fault
from one of the more bug-based ones by the method described here.


To tell if it ran off the stack, run it under dbx:


% dbx a.out


(dbx) catch SIGSEGV


(dbx) run


...


signal SEGV (segmentation violation) in


at 0xeff57708


(dbx) where


If you now see a call chain, then it hasn't run out of stack space.


If instead you see something like:


fetch at 0xeffe7a60 failed -- I/O error


(dbx)


then it probably has run out of stack space. That hex number is the stack address which
could not be mapped or retrieved.

Free download pdf