Re: [cc65] Need some help with a memory leak

From: Greg King <greg.king41verizon.net>
Date: 2010-05-05 02:11:16
From: "Payton Byrd"; on Tues., May 04, 2010; at 04:32 PM -0400
>
> Maybe I'm wrong, but here's how I interpret the code:
>
> currentNode = drive->tail;
> while(currentNode != NULL && currentNode->prev != NULL)
> {
>   if(currentNode->next != NULL)
>     free(currentNode->next);
>
>   currentNode = currentNode->prev;
> }
> if(currentNode != NULL)
>   free(currentNode);

> The first step sets currentNode to the tail of the list.
> Next, we loop until currentNode is NULL or currentNode->prev is NULL.
> In a directory of any files, that will be false, at least once.

No.  If there is only one file, then the loop's body won't be executed.

> Next, we look at currentNode->next; and, if it's not null, we free it.
> Next, we move to one node to the left.
> Once we complete the loop, currentNode should have both prev = NULL,
> and the pointer for next should be freed, ...

As soon as the loop reaches the first node in the list, it "looks
ahead", sees that currentNode->prev (always) is NULL, and stops.  It
_doesn't_ get a chance to handle that first node!  Therefore, the next
(second) node never is freed!

That "look ahead" is the bug.  It isn't needed because the "previous"
pointer is copied into the current pointer; and then, that current
pointer immediately is tested.
-------------------------------------------------------------

By the way, the usual method to remove a linked list is to free each
node while the loop actually is "sitting" on that node.  (Only one
link-pointer is needed in each node.)  The loop starts at the beginning
of the list, and walks through the list, from first to last.  It saves
the "next link" in a local variable, then frees the node.  Then, it
copies that saved link into the "current pointer", and repeats the loop.
That method requires only one NULL-pointer-test, instead of the three
tests that your method needs.

----------------------------------------------------------------------
To unsubscribe from the list send mail to majordomo@musoftware.de with
the string "unsubscribe cc65" in the body(!) of the mail.
Received on Wed May 5 02:17:52 2010

This archive was generated by hypermail 2.1.8 : 2010-05-05 02:17:55 CEST