Currently I'm trying to set up a member function for Student that reads a string from cin, is used as an argument for this function and then creates a Student object with the data. However, is it giving me a bad_alloc error. I know the function is getting the string but it gives this error after the new object is created.
Error:
./a.out
Please insert name for student:
Bob_Russel
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted
Constructor:
Student::Student(string tname){
name = tname;
}
Function:
Student Student::readStudent(istream &i){
Student *stud;
string y;
i >> y;
stud = new Student(y);
return *stud;
}
testStudent.cpp:
#include "Student.h"
int main(){
Student *stud3;
cout << "\nPlease insert name for student:\n";
stud3->readStudent(cin);
return 0;
}
Not only does the code leak memory (creating a new Student
in readStudent
that is never deleted), in main
you are using an uninitialized pointer to call readStudent
. Possibly this is corrupting your heap such that the call to new throws a std::bad_alloc
.
Take another look at C++ memory management and object lifetimes. There is really no need to use pointers at all here. As a starting point, your main
could be modified to this:
int main() {
Student stud3;
std::cout << "Please insert name for student:" << std::endl;
stud3.readStudent(std::cin);
}
It would perhaps also be better if you read in the name within main
(as a std::string
), and then pass the name directly to the Student
constructor:
int main() {
std::cout << "Please insert name for student:" << std::endl;
// Read in the name.
std::string name;
std::cin >> name;
// Create the student with the input name.
Student stud3(name);
}