freeing memory allocated for a linked list

Thu Oct 6 10:35:41 EDT 1994

I have a bug that shows up rarely in the r.le tracing program, usually 
after running for a long period of time on a large map.  The code 
below sets up and adds new members to a linked list, then goes through
the list freeing up the allocated memory:

typedef struct patch {
	int		att, num, n, s, e, w, npts;
	double		c_row, c_col;
	double		area, perim, long_axis;
	double		edge, core;
	int		*row:
	int		*col;
	struct patch	*next;

PATCH	*patch_list;

void trace(xxx)
PATCH	*ptrthis, *ptrnew, *ptrfirst;

ptrfirst = (PATCH *) NULL;

if (ptrnew = get_bd(yyy,zzz,etc.)) {

	/* if the get_bd routine finds a new patch and
	   returns a point to it */

   if (ptrfirst == (PATCH *) NULL)
      patch_list = ptrfirst = ptrthis = ptrnew;
   else {
      ptrthis = ptrfirst;
      while(ptrthis->next != (PATCH *) NULL)
         ptrthis = ptrthis->next;  /*find the end of list */
      ptrthis->next = ptrnew;
      ptrthis = ptrnew;

PATCH *get_bd(xxx,yyy,etc.)
PATCH	*patch;

patch = (PATCH *)G_calloc(1, sizeof(PATCH));
	/* allocate memory for a new member of patch list */

...code that assigns values to items in patch ...


The routine that drives the program and calls the trace() subroutine
above, then after using the patch list, frees up the memory allocated
for the list.  This is where the program produces a Bus Error, with
the statement "list_head = patch_list->next".  It seems that, if I
understand bus errors, there is a memory alignment problem.  Here's
the freeing code, that moves down through the list:

while(patch_list) {
   list_head = patch_list->next;
   patch_list = list_head;

Oops...I forgot to include the part of the code in the get_bd routine
that allocates memory for the col and row lists:

	patch->col = (int *)G_calloc(pts, sizeof(int));
	patch->row = (int *)G_calloc(pts, sizeof(int));

Most of the time the above code works fine.  Very rarely the bus error

I definitely am in over my head with this use of linked lists, as I am
only an advanced beginner at C.  I realize the above is a little
messy to figure out, but if you have a little time and could help, I
would appreciate it very much.  Any idea why the rare bus error?

	Bill Baker
	bakerwl at

More information about the grass-dev mailing list