Hey guys, I am trying to learn single linked lists and at first I was having some trouble but now my code works perfectly. At first my program would crash, and when I tried to debug it, it would always crash where ever I had a 'delete' operator within the functions. Such as here:
void add(node* addMe)
{
node* newItem=new node;
newItem=addMe;
newItem->next=head;
head=newItem;
//delete newItem;
}
void addNode(int num)
{
for(int i=0;i<num;i++)
{
node *pointer=new node;
cout<<"What is the name of family member #"<<i+1<<"?"<<endl;
cin>>pointer->name;
cout<<"What is the job title of family member #"<<i+1<<"?"<<endl;
cin>>pointer->jobTitle;
cout<<"how old is # "<<i+1<<"?"<<endl;
cin>>pointer->age;
cout<<"how much money does this person make ?"<<endl;
cin>>pointer->salary;
add(pointer);
//delete pointer;
}
}
So then I comment out the "delete" in these 2 methods, and all of a sudden the code works just fine. But I am confused, as to why my program was crashing when I DID have the 'delete'. I thought everytime I allocated memory using 'new', I am suppose to free the memory using 'delete'.
Here is my complete code that works and compiles just fine.
BUT if you DONT comment out the 'delete' in those 2 functions, then the program will crash. Can someone explain to me why?
#include <iostream>
#include <string>
using namespace std;
struct node
{
string name;
int age;
float salary;
string jobTitle;
node *next;
};
class Family
{
private:
int size;
node *head;
public:
Family()
{
size=0;
head=new node;
head=0;
}
~Family()
{
}
void add(node* addMe)
{
node* newItem=new node;
newItem=addMe;
newItem->next=head;
head=newItem;
//delete newItem;
}
void addNode(int num)
{
for(int i=0;i<num;i++)
{
node *pointer=new node;
cout<<"What is the name of family member #"<<i+1<<"?"<<endl;
cin>>pointer->name;
cout<<"What is the job title of family member #"<<i+1<<"?"<<endl;
cin>>pointer->jobTitle;
cout<<"how old is # "<<i+1<<"?"<<endl;
cin>>pointer->age;
cout<<"how much money does this person make ?"<<endl;
cin>>pointer->salary;
add(pointer);
//delete pointer;
}
}
void printMe(int num)
{
node *print=new node;
print=head;
for(int i=0;i<num;i++)
{
cout<<print->name<<endl;
cout<<print->age<<endl;
cout<<print->jobTitle<<endl;
cout<<print->salary<<endl;
print=print->next;
cout<<endl;
}
delete print;
}
};
void main()
{
Family *familyPointer=new Family;
int num;
cout<<"how many family members do you have?"<<endl;
cin>>num;
familyPointer->addNode(num);
familyPointer->printMe(num);
delete familyPointer;
system("PAUSE");
}