I encountered the following problem, and I don’t get any warnings or errors, just a program crash.
When I run in my menu printAll() after dummyData() initialisation. The moment I add one new student it just starts to loop the studentMenu().
Domain.h:
template <class T>
struct Array{
int length;
T * M;
Array( int size ) : length(size), M(new T[size])
{
}
~Array()
{
delete[] M;
}
};
template <class T>
struct Array{
int length;
T * M;
Array( int size ) : length(size), M(new T[size])
{
}
~Array()
{
delete[] M;
}
};
template <class T>
void addStudent(int a, int b, std::string c,Array <T> A){
A.M[a].setStudent(a,b,c);
}
template <class T>
void DummyDataStudents(Array <T> A){
for(int i=1; i<15; i++){
A.M[i].setStudent(i, i,"student");
}
cout<<"Done Students"<<endl;
}
Controller.h
template <class T>
void _addStudent(Array <T> &A){
int a,b;
string c;
cout<<"Enter ID:"<<endl;
cin>>a;
cout<<"Enter Group:"<<endl;
cin>>b;
cout<<"Enter Name:"<<endl;
cin>>c;
addStudent(a,b,c,A);
}
Student.cpp:
void Student::setStudent(int a,int b,string c){
this->ID = a;
this->group = b;
this->name = c;
}
Menu.cpp:
void Menu::mainMenu(Array <Student> &DBst,Array <Assignment> &DBas){
showMainMenu();
int ret = Menu::intInputHandler();
switch(ret){
case 1:studentMenu(DBst,DBas);break;
case 2:assignmentMenu(DBst,DBas);break;
case 3:statsMenu(DBst,DBas);break;
case 4:_printAll(DBst,DBas);break;
case 0:break;
default:cout<<"Wrong option selected!";break;
}
Menu::mainMenu(DBst,DBas);
}
void Menu::studentMenu(Array <Student> &DBst,Array <Assignment> &DBas){
showStudentMenu();
int ret = Menu::intInputHandler();
switch(ret){
case 1:_addStudent(DBst);break;
case 2:break;
case 3:break;
case 4:break;
case 5:_printAllStud(DBst);break;
case 6:break;
case 0:mainMenu(DBst,DBas);break;
default:cout<<"Wrong option selected!";break;
}
Menu::studentMenu(DBst,DBas);
}
Main.cpp:
int main(){
//Main function of the program
DummyDataStudents(DBst);
DBst.M[10].setStudent(1,10,"sadasd"); //works just fine
DBst.M[10].printStudent();cout<<endl;
Menu main;
main.mainMenu(DBst,DBas);
DBst.~Array();
DBas.~Array();
return 0;
}
///I think this should be enough to understand. When I add a new student I get loops of menu printing until it crashes; if I call printall() I get a crash directly. Please help and sorry for the long code.
This is a problem:
the
ArrayAis being passed by value, so it is being copied meaning there are now two instances ofArraypointing to the same internal arrayMas there is no copy constructor defined forArrayso a default copy constructor is generated. WhenaddStudent()returns the internal arrayMis being deleted by the instance ofArraylocal to the function. This leaves the remaining instance ofArrayAwith a dangling pointer.Either implement a copy constructor and assignment operator (which I don’t think you want to do) or make
Arraynon-copyable be declaring the copy constructor and assignment operatorprivate.