Archived

This topic is now archived and is closed to further replies.

oveja-carnivora

pointers, link list

Recommended Posts

Hi, I am using a link list in VC++ 6 for a project Im working on. How do I make sure that I have cleaned up the info in the link list? Will just setting all the pointers in the list to NULL work? how do I actualy clear the memory that it is using? will t automaticly clear it when I exit the function that they were declared in? thanxs

Share this post


Link to post
Share on other sites
Did you create the "nodes" with NEW? If so, you''ll need to call delete on them for every time you used NEW to free up the memory you used.

Setting a pointer to NULL doesn''t delete the memory, it only removes your pointer(s) to that memory making it in accessible.

You''ll have to walk through your linked list and call delete on each node.

R.

Share this post


Link to post
Share on other sites
No, just setting the pointers to NULL doesn''t cut it (you don''t have garbage collection in C/C++ ... do you come from the Java world ? ).

You have to call delete (C++) or free (C) on every pointer you have allocated. Then, you can set them to NULL. It''s safer, unless you know you''re going to discard the structure containing the pointer itself, in which case it doesn''t matter.

Share this post


Link to post
Share on other sites
A good way to delete an entire linked list would be to use a recursive algorithm..


void del_list(node *currentNode) {
if (currentNode->nextNode != NULL)
del_list(currentNode->nextNode);

delete currentNode->nextNode;
currentNode->nextNode = NULL;
}


.. something like that.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster

  
ListType * pDel;
for( ListType * pTemp = pHeadOfList; pTemp; )
{
pDel = pTemp;
pTemp = pTemp->pNext;

if( pDel )
{ delete pDel; // Unless you used malloc, then free() is correct.

pDel = NULL;
}
}

That should work for ya.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
quote:
Original post by oveja-carnivora
Annoymous, you said that delete would work unless I used memalloc. I was working from MSDN and I did use malloc, thats the only way I could find in there to make a link list. how else could I do it?


Just use the free function instead of delete if you used malloc.

If you want to know how else to allocate memory, look up the ''new'' keyword.

Share this post


Link to post
Share on other sites