I am practcing c++'s new/delete, hashfunction and linked.
I made a practice by myself.
I have a struct which is
typedef struct student
{
int id;
string fName;
string lName;
student * nextStudent;
}Student;
Then in main function, I define an array of student
Student * table = new Student [10];
I have my own hash function which takes the id, and change to 0-9. I want to add a student I do following
void addStudent(int studentId, string firstName, string lastName, Student *table)
{
// using hash function, convert the id into hashed id
int hashedID = hashFunction( studentId );
Student * pointer = &table[hashedID];
while(pointer->nextStudent !=NULL){
pointer = pointer->nextStudent;
}
// once we reach to the student who has NULL in nextStudent
// add student
Student *tmp = new Student;
tmp->id = studentId;
tmp->fName = firstName;
tmp->lName = lastName;
tmp->nextStudent = NULL;
// link
pointer->nextStudent = tmp;
}
I tested it, it seems fine.
The problem is deletion. Since student variables are stored in dynamic memeory, I need to use delete.
The following is my code.
void deleteAll(Student *table, int len)
{
for (int i = 0; i < len; i++)
{
Student* tmp = &table[i];
// delete student info except the last one
while ( tmp -> nextStudent !=NULL){
Student* tmp2;
tmp2 = tmp;
tmp = tmp->nextStudent;
delete tmp2;
}
}
}
I visited every student varialbes ane do the deletion. I cannot find any probelm in my deletion funtion...
This is what I got after run..
malloc: *** error for object 0x7f85f1404b18: pointer being freed was not allocated
I have no clue what I have done wrong.. Can you help me?
EDIT...
As you guys metion I added "delete [] table" in the main funtion.. Also, I remove "delete tmp" in deleteAll function; i think "delete [] table" will handle that part.
Still does not work..
By the way I forgot to added initTable function in the initial post. initTable initialize the table...
void initTable (Student *table, int len)
{
for (int i = 0; i < len; ++i)
{
table[i].nextStudent = NULL;
}
}
Thank you.
tableafter you allocate it? - 1201ProgramAlarmtable[i]wasn't allocated individually, it was allocated as part of an array. All subsequent students in the linked list can be deleted withdelete, buttable[i]must only be deleted by deleting the whole array (delete[] table;). - Jonathan Potter