GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 25-Oct-2006, 12:34
dabigmooish's Avatar
dabigmooish dabigmooish is offline
Member
 
Join Date: May 2004
Location: Baltimore (middle of Canton)
Posts: 165
dabigmooish will become famous soon enough

Linked list memory question


I've written a linked list class to use with another program I'm making. I wanted to make sure that I clean up all the used memory. I added a destructor to my class. Will that be enough to clear the memory up? I've tried to add delete statements at the end of each function but most of them caused the function to no longer work correctly. The following is the class definitions (The destructor is at the bottom)

CPP / C++ / C Code:


#include <iostream>
#include <string>
#include "linked.h"


//Constructor
linklist::linklist()
{

     head = NULL;

}

void linklist::AppendNode( string sym )
{
     
     node *temp1,*temp2;
 
     if( head == NULL )     //If the list is empty start a new one
     {
          head = new node;
          head->symbol = sym;
          head->next = NULL;     //set the new node as the tail
     }
     else //If the head exist then...
     {
          temp1 = head; //Copy the node list

          while( temp1->next != NULL ) //move to the end of the list
          {
               temp1 = temp1->next;
          }


          temp2 = new node;     //create a new node
          temp2->symbol = sym;  //add data to the new node
          temp2->next = NULL;   //make the node point to the end
          temp1->next = temp2;  //set temp1->next to point to the new node
     }

}

void linklist::AddAsFirstNode( string sym )
{

     node *temp1;          //declare a new node

     temp1 = new node;     //create a new node

     temp1->symbol = sym;  //fill the node with data
     temp1->next = head;   //set up the pointer head

     head = temp1;         //sets head as the first node in the list

}

bool linklist::InsertNode( string searchSym, string insertSym )
{

     node *temp1, *temp2;          //Declares temp node pointers
     bool returnValue = false;     //defaults to false     
  
     temp1 = head;                 //sets first node equal to head

     while(temp1 != NULL)    //move until you get to the end of the head
     {
          
    
          if(temp1->symbol == searchSym)
          {
               
               temp2 = new node;              //declares a new node
               temp2->symbol = insertSym;     //files the new node with data
               temp2->next = temp1->next;     //sets temp2 to point to the next node
               temp1->next = temp2;           //points temp1 to the new node
              
               returnValue = true;            //sets the return value to true
          }   
   
          temp1 = temp1->next;     //advance to the next node

     }


     return(returnValue);

}


bool linklist::DeleteNode( string sym )
{

     bool returnValue = false;     //defaults to false
     node *temp1, *temp2;          //declares two node pointers
     
     temp1 = head;                 //sets temp1 to equal head
     
     while(temp1 != NULL)          //checks until the end of the list
     {

          temp2 = temp1;           //sets temp2 equal to the temp1, basically the node before temp1 since 
				   // that is moved "up" the list in the next step
          temp1 = temp1->next;      //moves temp1 "up" the list

          if(head->symbol == sym)     //checks to see if head is the node to delete
          {
               head = temp2->next;    //sets head as the second node
               returnValue = true;       //changes the return value to be true
               temp1 = NULL;          //sets temp1 to NULL to escape the while loop
          }
          else if(temp1->symbol == sym)          //Checks if temp1 is to be deleted
          {
               
               temp2->next = temp1->next;   //points the previous pointer to the next one
                                            //basically "deleting" node temp1
               returnValue = true;          //changes the return value to be true
               temp1 = NULL;                //sets temp1 equal to NULL to escape while loop
          }
     

     }


     return(returnValue);     //returns True of False

}

void linklist::DisplayNodes()
{
     node *temp1;     //Declares a temp node
     
     int i = 0;       //sets the counter to 0 incase the head is empty

     temp1 = head;    //temp1 will equal head    

     while(temp1 != NULL) //continue loop until empty
     {
          i++;   //since the head is not empty add 1 to the counter and display the info

          cout << "Element " << i << " is ";
          cout << temp1->symbol << endl;

          temp1 = temp1->next; //move to next node
     }
   

}


int linklist::CountNodes()
{
     int tempCount = 0;     //if the head is empty the count is zero

     node *temp1;           //declares a temp node

    
     // sets temp1 equal to head, checks until temp1 is NULL,
     // "increments" temp1 by making it equal to the next node
     // on the list until it is NULL.  With each iteration 
     // increase the count.
     for(temp1 = head; temp1 != NULL; temp1 = temp1->next)
     {
          tempCount++;
     }

     return(tempCount);     //returns the number of nodes
}

string linklist::ReturnValue(int num)
{

     node *temp1;	//declares a node pointer
     string tempS;	//holds the contents of the numth element

     temp1 = head;	//sets temp1 to the start of the list

     if(num <= CountNodes() && num > 0) //checks bounds
     {
          for(int i = 1; i < num; i++) // move up the list until the numth 
          {                            // element is found
               temp1 = temp1->next;
          }
          tempS = temp1->symbol;       //set tempS

     }
     else
     {
          tempS="INVALID";
     }

  

     return(tempS);

}     


linklist::~linklist()
{

     node *temp1;     //declares a temp node

     
     while(head != NULL)  //until head is null do the following
     {

          temp1 = head->next; //set temp1 equal to the next node
          delete head;        //delete the first node (making temp1 the new first node)
          head = temp1;       //make head the first node again.
     }

     delete temp1;
}

__________________
"To argue with a person who has renounced the use of reason is like administering medicine to the dead."
-Thomas Paine
www.sullivan-county.com/deism.htm
  #2  
Old 25-Oct-2006, 14:42
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 4,720
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: Linked list memory question


Quote:
Originally Posted by dabigmooish
I wanted to make sure that I clean up all the used memory.

Two quickies, off the top of my head:

With de-allocating memory, there are two ways to go wrong.


1. Don't delete enough (that is leave something orphaned with nothing pointing to it so that it can't be deleted when the object goes out of scope).

2. Delete too much (that is, delete something that wasn't obtained from new).

For example, here's the first one:

1. In function deleteNode, as you unlink a node from the list, you must delete the memory then and there, since the destructor will not be able to find it later.


And here's the second one

2. In your destructor, you have the following

CPP / C++ / C Code:
linklist::~linklist()
{

     node *temp1;     //declares a temp node 

     
     while(head != NULL)  //until head is null do the following
     {

          temp1 = head->next; //set temp1 equal to the next node
          delete head;        //delete the first node (making temp1 the new first node)
          head = temp1;       //make head the first node again.
     }

     delete temp1;
}

You musn't delete temp1 after the loop, since, if the list is empty, you don't go through the loop at all, and you will be deleting something whose address you didn't get from new. That's a no-no.

On the other hand, if the list isn't empty, the loop takes care of deleting all of the nodes in the list, so the extra delete after the loop is unnecessary. (In other words, it works OK without that last delete.)

Regards,

Dave
  #3  
Old 26-Oct-2006, 08:17
dabigmooish's Avatar
dabigmooish dabigmooish is offline
Member
 
Join Date: May 2004
Location: Baltimore (middle of Canton)
Posts: 165
dabigmooish will become famous soon enough

Re: Linked list memory question


Thanks for the tips dave. I like pointers, hate memory management.
__________________
"To argue with a person who has renounced the use of reason is like administering medicine to the dead."
-Thomas Paine
www.sullivan-county.com/deism.htm
  #4  
Old 31-Oct-2006, 00:05
Gurumavali Gurumavali is offline
New Member
 
Join Date: Oct 2006
Posts: 1
Gurumavali is on a distinguished road
Arrow

Re: Linked list memory question


Usually before deleteing, make habit to check it first and then use delete
 
 

Recent GIDBlogDeveloping GUIs with wxPython (Part 4) by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Airport Log program using 3D linked List : problem reading from file batrsau C Programming Language 11 29-Feb-2008 07:44
[Include] Doubly-linked List dsmith C Programming Language 6 14-Apr-2006 13:12
linked list error message Krandygrl00 C++ Forum 4 22-Jun-2005 14:13
search linked list itsmecathys C++ Forum 20 18-Apr-2005 01:34

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 18:01.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.