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.