Question

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;

}
Was it helpful?

Solution

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);
 }

OTHER TIPS

It looks like you're trying to implement a factory method. If that's the case, then you're missing the static keyword and the correct syntax for the readStudent call.

class Student{
public:
    Student(std::string tname);
    static Student* readStudent(std::istream &i);
private:
    std::string name
};

Student::Student(std::string tname) {
    name = tname;
}

Student* Student::readStudent(std::istream &i){
    std::string y;
    i >> y;
    return new Student(y);
}

int main(int argc, char* argv[]){
    Student *stud3 = NULL;

    std::cout << "\nPlease insert name for student:\n";

    stud3 = Student::readStudent(cin);

    return 0;
}

You are allocating on the heap using new and never freeing it, thus you run out of memory and get a bad_alloc. For every new there should be a delete.

This will not throw bad_alloc:

Student Student::readStudent(std::istream& i)
{        
   std::string y;    
   i >> y;    
   return Student(y);    
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top