为什么这会产生 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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
代码不仅会泄漏内存(在
readStudent
中创建一个永远不会被删除的新Student
),而且在main
中,您使用了一个未初始化的指针调用readStudent。这可能会损坏您的堆,从而导致对 new 的调用引发std::bad_alloc
。再看一下 C++ 内存管理和对象生命周期。这里实际上根本不需要使用指针。作为起点,您的
main
可以修改为:如果您在
main
中读取名称(作为std:: string
),然后将名称直接传递给Student
构造函数:Not only does the code leak memory (creating a new
Student
inreadStudent
that is never deleted), inmain
you are using an uninitialized pointer to callreadStudent
. Possibly this is corrupting your heap such that the call to new throws astd::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:It would perhaps also be better if you read in the name within
main
(as astd::string
), and then pass the name directly to theStudent
constructor:看起来您正在尝试实现工厂方法。如果是这种情况,那么您缺少 static 关键字和 readStudent 调用的正确语法。
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.
您使用 new 在堆上分配并且从不释放它,因此您耗尽了内存并得到了 bad_alloc。对于每个
新
都应该有一个删除
。这不会抛出 bad_alloc:
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 adelete
.This will not throw bad_alloc: