I have a class call Roster which consists name of the course and instructor and a pointer points to a array of pointers to Student objects (Student** slist) as private data. In a member function called delstudent() which delete students object by pointers. The program compiles and runs, but throw me a double deletion messenge whenever I try to delete a student. Can anybody take a look of my delstudent() function code, point to me where I did wrong? Thank you.
problem occurs at the excution of the: delete slist[i] in delstudent() function.
Here is the error messenger I get:
hw6(370) malloc: *** error for object 0x7fff5fbff770: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Program received signal: “SIGABRT”.
Here is my private data, constructor, addstudent(Student* s) function, delstudent() function and destructor
1 2 3 4 5 6 7 8 9 10
private:
string courseN;
string instrN;
int courseCode;
int credits;
int size; //keep track of the size of the array of pointers
int capacity;
void sort();
void grow();
Student** slist; //a list of pointers point to Student object who take a certian class
1 2 3 4 5 6 7 8 9 10
Roster::Roster(string cn, int cc, int cs, string instructor)
{
courseN=cn;
courseCode=cc;
credits=cs;
instrN=instructor;
capacity=20;
size=0;
slist=new Student*[capacity];
}
void Roster::delstudent()
{
string first, last;
cout << "Which student do u want to delete?\n";
cout << "Please Enter the last name of this student\n";
cin>>last;
//last[0]=toupper(last[0]);
cout << "Enter the first name of this student.\n";
cin>>first;
//first[0]=toupper(first[0]);
for (int i=0; i < size; i++)
{
if( slist[i]->getlname()==last && slist[i]->getfname()==first )
{
delete slist[i]; //if found, delete the memory allocation pointed by this pointer
for (int j=i; j < size; j++)
{
slist[j] = slist[j+1]; //after deletion, points to the next pointer points
}
size--;
return;
}
}
cout << "Student not found!!!\n";
cout <<"Programme will terminate now\n";
exit(0);
}
What do slist, size, and i look like at this point? Clearly slist[i] is not being allocated by new, or has already been deleted previously. I assume this doesn't occur on the first attempt to delete?
I input 2 students, so the size is 2, slist[0] points to the first student object, slist[1] points to second student object, slist[2] points to NULL, and try to delete the second one(slist[1]).
when the names checks, at this point i=1, size=2, slist[1] is to be deleted, at this point I placed a break-point just before the deletion, everything is fine, when comes to the deletion statement, it throws me a double deletion messenger.
Is that your exact code? If so, I don't see you actually adding the students with addstudent(). And also, those are statically allocated variables so if you pass their address then try to delete them, it will fail as you are not allowed to delete a variable allocated on the stack.