Thread: Link List / Dynamic memory

  1. #1
    Registered User
    Join Date
    Sep 2006
    Location
    vancouver wa
    Posts
    221

    Link List / Dynamic memory

    In my project i am loading food items from a file, and adding them to a link list.
    my function where i add the foods is where i have a memory leak. How do i de- allocate memory in that function? If i delete newNode, then when i try to list the food my program crashes. But, if i dont delete that memory it doesnt crash and displays the foods. I am using crtdbg.h to test for leaks.
    Here is the 2 functions.

    Is there a way i can delete newNode it in a destructor? or should i pass it out and deallocate?

    Code:
    void FoodLists::addAtEnd(const Nutricalc &afood)
    {
    char name[SIZE];
    
    	   Node * newNode = new Node;
                   afood.getname(name);
    	   newNode->Data.setname(name);
                   newNode->Data.setCategory(afood.getCategory());
    	   newNode->Data.setcalories(afood.getcalories());
    	   newNode->Data.setcarbs(afood.getcarbs());
    	   newNode->Data.setcholesterol(afood.getcholesterol());
    	   newNode->Data.setfat(afood.getfat());
    	   newNode->Data.setsodium(afood.getsodium());
    	   newNode->Data.setprotien(afood.getprotien());
                   newNode->next = NULL;
    
    	//increment the size of the list
    	size++;
    
    	if(tail == NULL)
    	{
    	head = newNode;
    	tail = newNode;
    	}
    	else
    	{
    	
                 tail->next = newNode;
                 tail = newNode;
    	}
    }
    Code:
    void FoodLists::listFood()
    {
    
    
      //int i;
      char categoryDescription[ARRAY_SIZE];   // holds the name of the categories
      char name[SIZE];
    
      Node * current = head;
    
      while(current)
      {
      current->Data.getname(name);
       
      convertCategory(current->Data.getCategory(), categoryDescription); 
      cout << endl;
      //cout << setfill(' ') << left << setw(17) << "index:" ;
      //cout <<  << endl;
      cout << setfill(' ') << left << setw(17) << "name:" ;
      cout << name << endl;
      cout << setfill(' ') << left << setw(17) << "category:" ;
      cout   << categoryDescription << endl;
      cout << fixed << showpoint << setprecision(2);
      cout << setfill(' ') << left << setw(17) << "calories:" ;
      cout << current->Data.getcalories() << endl;
      cout << setfill(' ') << left << setw(17) << "carbohydrates:" ;
      cout   << current->Data.getcarbs() << setw(18)<< " grams" << endl;
      cout << setfill(' ') << left << setw(17) << "fat:"; 
      cout	<< current->Data.getfat() << setw(14)<< " grams" << endl;
      cout << setfill(' ') << left << setw(17) << "cholesterol:" ;
      cout	<< current->Data.getcholesterol() << setw(19)<< " grams" << endl;
      cout << setfill(' ') << left << setw(17) << "sodium:"; 
      cout	<< current->Data.getsodium() << setw(14)<< " grams" << endl;
      cout << setfill(' ') << left << setw(17) << "protien:" ;
      cout  << current->Data.getprotien() << setw(14)<< " grams" << endl;
      cout << endl;
      cout << ">";
      current = current->next;
    	}
    }
    Sorry, its not formatted better, it came out bad when i pasted it!
    any help is much appreciated.
    Last edited by mrsirpoopsalot; 05-24-2009 at 12:15 AM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > Sorry, its not formatted better, it came out bad when i pasted it!
    Fix your IDE so that it only uses spaces for indenting.
    All spaces - good
    All tabs - ok, but produces extreme indents when posted
    A mix of spaces and tabs - a disaster
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Sep 2006
    Location
    vancouver wa
    Posts
    221
    Code:
    void FoodLists::addAtEnd(const Nutricalc &afood)
    {
           char name[SIZE];
           Node * newNode = new Node;
    
           afood.getname(name);
           newNode->Data.setname(name);
           newNode->Data.setCategory(afood.getCategory());
           newNode->Data.setcalories(afood.getcalories());
           newNode->Data.setcarbs(afood.getcarbs());
           newNode->Data.setcholesterol(afood.getcholesterol());
           newNode->Data.setfat(afood.getfat());
           newNode->Data.setsodium(afood.getsodium());
           newNode->Data.setprotien(afood.getprotien());
           newNode->next = NULL;
    
    	//increment the size of the list
           size++;
    
           if(tail == NULL)
           {
           head = newNode;
           tail = newNode;
           }
           else
           {
           tail->next = newNode;
           tail = newNode;
           }
    
    }
    Code:
    void FoodLists::listFood()
    {
    
      char categoryDescription[ARRAY_SIZE];   // holds the name of the categories
      char name[SIZE];
      Node * current = head;
    
      while(current)
      {
      current->Data.getname(name);
       
      convertCategory(current->Data.getCategory(), categoryDescription); 
      cout << endl;
      cout << setfill(' ') << left << setw(17) << "name:" ;
      cout << name << endl;
      cout << setfill(' ') << left << setw(17) << "category:" ;
      cout   << categoryDescription << endl;
      cout << fixed << showpoint << setprecision(2);
      cout << setfill(' ') << left << setw(17) << "calories:" ;
      cout << current->Data.getcalories() << endl;
      cout << setfill(' ') << left << setw(17) << "carbohydrates:" ;
      cout   << current->Data.getcarbs() << setw(18)<< " grams" << endl;
      cout << setfill(' ') << left << setw(17) << "fat:"; 
      cout	<< current->Data.getfat() << setw(14)<< " grams" << endl;
      cout << setfill(' ') << left << setw(17) << "cholesterol:" ;
      cout	<< current->Data.getcholesterol() << setw(19)<< " grams" << endl;
      cout << setfill(' ') << left << setw(17) << "sodium:"; 
      cout	<< current->Data.getsodium() << setw(14)<< " grams" << endl;
      cout << setfill(' ') << left << setw(17) << "protien:" ;
      cout  << current->Data.getprotien() << setw(14)<< " grams" << endl;
      cout << endl;
      cout << ">";
      current = current->next;
      }
    }
    I fixed the formatting, will someone please help me? why cant i delete newNode? and have list work without crashing?
    thank you,
    Corey

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Don't know - I see no direct reason why it would crash. Have you tried running in a debugger to see where it actually crashes?

    There's a spelling mistake in protein:
    Code:
           newNode->Data.setprotien(afood.getprotien());
    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  5. #5
    Registered User
    Join Date
    Sep 2006
    Location
    vancouver wa
    Posts
    221
    ok, for some reason it is crashing when i run it and just close it.
    error: This may be due to a corruption of the heap, and indicates a bug

    If i try try to do something like list foods i get a different error:
    Unhandled exception at 0x102aecd1 (msvcr80d.dll) in Lab2.exe:

    It is due to the delete newNode;

    how can i delete the memory so i do not have a leak in that function?
    Code:
    void FoodLists::addAtEnd(const Nutricalc &afood)
    {
    
           char name[SIZE];
    
    	   Node * newNode = new Node;
           afood.getname(name);
    	   newNode->Data.setname(name);
           newNode->Data.setCategory(afood.getCategory());
    	   newNode->Data.setcalories(afood.getcalories());
    	   newNode->Data.setcarbs(afood.getcarbs());
    	   newNode->Data.setcholesterol(afood.getcholesterol());
    	   newNode->Data.setfat(afood.getfat());
    	   newNode->Data.setsodium(afood.getsodium());
    	   newNode->Data.setprotien(afood.getprotien());
           newNode->next = NULL;
    
    	//increment the size of the list
    	size++;
    
    	if(tail == NULL)
    	{
    	head = newNode;
    	tail = newNode;
    	}
    	else
    	{
    	
        tail->next = newNode;
        tail = newNode;
    	}
    
       delete newNode;
    
    }
    thank you

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    For the last time, fix your IDE, and make use of the preview button before pressing submit.

    > how can i delete the memory so i do not have a leak in that function?
    Put it all in the destructor for the class.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  7. #7
    Registered User
    Join Date
    Sep 2006
    Location
    vancouver wa
    Posts
    221
    Link list are pretty new to me, so i am still trying to grasp them.
    How can i delete newNode in a destructor?
    Code:
    void FoodLists::addAtEnd(const Nutricalc &afood)
    {
    
           char name[SIZE];
    
           Node * newNode = new Node;
           afood.getname(name);
           newNode->Data.setname(name);
           newNode->Data.setCategory(afood.getCategory());
           newNode->Data.setcalories(afood.getcalories());
           newNode->Data.setcarbs(afood.getcarbs());
           newNode->Data.setcholesterol(afood.getcholesterol());
           newNode->Data.setfat(afood.getfat());
           newNode->Data.setsodium(afood.getsodium());
           newNode->Data.setprotien(afood.getprotien());
           newNode->next = NULL;
    Code:
    FoodLists::~FoodLists()
    {
    
    	
      Node * current;
      while(head != NULL)
      {
      current = head->next;
      delete head;
      head = current;
      }
    
    
    }
    Last edited by mrsirpoopsalot; 05-25-2009 at 02:08 AM.

  8. #8
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    The destructor looks ok to me.

    Are you using visual studio or a Dev-CPP/Code::Blocks IDE? You should be able to look at the trace-back to see where the code is crashing.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  9. #9
    Registered User
    Join Date
    Sep 2006
    Location
    vancouver wa
    Posts
    221
    I am using Visual Studio.

    If i de-allocate the memory in that function the program will crash.
    I am not sure how to de allocate that created memory!
    it was suggested that i do it in the destructor, but the memory was created in that function so, the destructor wont recognize newNode to de-allocate it.

    Code:
    void FoodLists::addAtEnd(const Nutricalc &afood)
    {
    
           char name[SIZE];
    
           Node *newNode = new Node;
           afood.getname(name);
           newNode->Data.setname(name);
           newNode->Data.setCategory(afood.getCategory());
           newNode->Data.setcalories(afood.getcalories());
           newNode->Data.setcarbs(afood.getcarbs());
           newNode->Data.setcholesterol(afood.getcholesterol());
           newNode->Data.setfat(afood.getfat());
           newNode->Data.setsodium(afood.getsodium());
           newNode->Data.setprotien(afood.getprotien());
           newNode->next = NULL;
    
    	//increment the size of the list
           size++;
    
           if(tail == NULL)
           {
           head = newNode;
           tail = newNode;
           }
           else
           {
    	
           tail->next = newNode;
           tail = newNode;
           }
    
        //delete newNode;  // causes crash
    
    }
    I am sure this is where my memory leak is. I thought i would have to delete it in the function i created it in?

  10. #10
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > newNode->Data.setname(name);
    Does this also call new for a char array, to copy the name into?
    It too will need to be freed when you run the dtor
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  11. #11
    The larch
    Join Date
    May 2006
    Posts
    3,573
    it was suggested that i do it in the destructor, but the memory was created in that function so, the destructor wont recognize newNode to de-allocate it.
    But you have the pointers to the memory which you store in the linked list and which you can access at any time. In any case, you cannot delete objects before you have finished using them. Part of the reason for dynamic allocation is that the object outlives the scope (function) where it was created.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  12. #12
    Registered User
    Join Date
    Sep 2006
    Location
    vancouver wa
    Posts
    221
    Salem,
    im suspecting this could be the cause of the leak?
    But, dont the destructor take care of that?

    Code:
    void Nutricalc::setname(char newName[])
    {
    
    if(name != NULL)
    {
      delete [] name;
      name = new char[strlen(newName)+1];
      strcpy(name, newName);
      }
      else
      delete [] name;
      }
    Code:
    Nutricalc::~Nutricalc()
    {
    
      if(name)
      {
      delete [] name;
      name = NULL;
      }
    
    }

  13. #13
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Your setname looks wrong. If the name is NULL, you delete it, which in itself is harmless [a consequence of this is that you can remove the "if (name)" part from your destructor]. But shouldn't you set the new name EVEN if the original name is NULL?

    Is name initialized to NULL?

    Oh, and could you not do:
    Code:
    newNode.Data = afood;
    instead of assigning each value independently.

    And your indentation sucks, but I think that has been brought up before....

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  14. #14
    Hail to the king, baby. Akkernight's Avatar
    Join Date
    Oct 2008
    Location
    Faroe Islands
    Posts
    717
    Linked lists... So C style xP I guess it's good to learn tho >.>
    Also, you could use a loop that deletes all the objects of the linked list...
    Currently research OpenGL

  15. #15
    Registered User
    Join Date
    Sep 2006
    Location
    vancouver wa
    Posts
    221
    I have tried to make my identation better!
    I have 2 classes and one of the destructors is not being called at all.
    I set a break point on both destructors and one is not being called at all.

    Code:
    Nutricalc::Nutricalc()
    {
    name = new char[SIZE];
    strcpy(name, "no name");
    category = nCategory;
    calories =0;
    carbs =0;
    fat=0;
    cholesterol=0;
    sodium=0;
    protien=0;
    }
    Not being called
    Code:
    FoodLists::~FoodLists()
    {
    	
    Node * current;
    while(head != NULL)
    {
      current = head->next;
      delete head;
      head = current;
    }
    
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. To find the memory leaks without using any tools
    By asadullah in forum C Programming
    Replies: 2
    Last Post: 05-12-2008, 07:54 AM
  2. Memory Allocation for self made Linked List
    By jsimpson in forum C Programming
    Replies: 5
    Last Post: 03-10-2006, 02:14 AM
  3. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM
  4. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM