pointers, link list

Started by
7 comments, last by oveja-carnivora 22 years, 3 months ago
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
Advertisement
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.
so if I go thru the entire link list setting *currentPtr to NULL then that wil take care of it?

EDIT: would I also need to set currentPtr to NULL?

Edited by - oveja-carnivora on January 14, 2002 11:37:30 AM
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.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
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.

  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.  
thanks
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?
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.

This topic is closed to new replies.

Advertisement