为什么会出现bad_alloc错误?

时间:2011-11-21 12:32:28

标签: c++ istream bad-alloc

目前我正在尝试为Student设置成员函数,该函数从cin读取字符串,用作此函数的参数,然后使用数据创建Student对象。但是,它是否给我一个bad_alloc错误。我知道函数正在获取字符串,但在创建新对象后会出现此错误。

错误:

./a.out

Please insert name for student:
Bob_Russel
terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
Aborted

构造

Student::Student(string tname){

  name = tname;

}

功能:

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;

}

3 个答案:

答案 0 :(得分:7)

代码泄露内存(在Student中创建一个永不删除的新readStudent)不仅在main中使用未初始化的指针来调用readStudent 。可能这会损坏您的堆,以致对new的调用抛出std::bad_alloc

再看看C ++内存管理和对象生命周期。这里根本没有必要使用指针。作为起点,您的main可以修改为:

int main() {
    Student stud3;
    std::cout << "Please insert name for student:" << std::endl;
    stud3.readStudent(std::cin);
}

如果您在main中读取名称(作为std::string),然后将名称直接传递给Student构造函数,那也许会更好:

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

答案 1 :(得分:1)

看起来您正在尝试实施工厂方法。如果是这种情况,那么您将缺少static关键字和readStudent调用的正确语法。

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

答案 2 :(得分:-1)

您正在使用new分配堆,并且永远不会释放它,因此您的内存不足并获得bad_alloc。对于每个new,应该有一个delete

这不会抛出bad_alloc:

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