Re: Extraction Crash

From: Ron Cole (rcole@EZY.NET)
Date: 10/20/97


>-+There was quite a bit of discussion a long time ago
>-+about using <struct>->next in loop conditions.
>-+If I remember correctly, it could all be summarized with:
>-+don't do it.

It's not whether you use for or while, it's whether you understand what the for
command does, and the dangers of allowing it to access freed data.  These 2
snippets are equally flawed:

for (obj = list; obj; obj = obj->next)
  free(obj);

obj=list;
while (obj) {
  free(obj);
  obj = obj->next;
}

As a matter of fact, they should generate pretty much identical code.  When you
are walking down a linked list, it's a Good Idea(tm) to save the next object,
before you start molesting the current one.

for (obj = list; obj; obj = next) {
  next = obj->next;
  free(obj);
}

You could also call a function recursively to do it like so:

void ofree(obj)
{
  if (obj->next) ofree(obj->next);
  free(obj);
}

ofree(list);

This frees the list starting from the end and works backwards.

Ron

PS:  I know most of you knew this already, but for some new coders, this is one
of those "light coming on" things, where suddenly all that linked list/pointer
stuff makes sense...  :-)


     +------------------------------------------------------------+
     | Ensure that you have read the CircleMUD Mailing List FAQ:  |
     | http://democracy.queensu.ca/~fletcher/Circle/list-faq.html |
     +------------------------------------------------------------+



This archive was generated by hypermail 2b30 : 12/08/00 PST