关于:'std::bad_alloc'实例
regarding: instance of 'std::bad_alloc'
我读了其他的帖子,但是没有一个有帮助。这段代码没有错误,但是有bad_alloc错误…
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char super[25];
char name[25],last_name[25];
int length;
char *sym = "#";
char *buffer;
ofstream outfile;
outfile.open("farses.dat",ios::app);
cout << "Writing to the file" << endl;
cout << "Enter your First Name: ";
cin >> name;
outfile << *sym;
outfile << name << endl;
cout << "Enter your Last Name: ";
cin >> last_name;
outfile << *sym;
outfile << last_name << endl;
cout << "Enter The Sentence : ";
cin.getline(super,25);
outfile << super << endl;
outfile.close();
ifstream infile;
infile.open("frases.dat");
infile.seekg(0, ios::end);
length = infile.tellg();
infile.seekg(0,ios::beg);
buffer = new char[length];
infile.read(buffer , length);
cout << "nnReading from file nn" << endl;
cout << buffer << endl;
infile.close();
return 0;
}
这段代码在进入句子语句后终止。我猜getline()函数引起了问题,但是当我尝试其他两个语句(name和last_name)时,getline(),它工作得很好。我甚至把字符限制也降低到5,但是在句子语句之后还是抛出
经验法则,不要欺骗自己认为代码没有错误。尤其是当你明显出错的时候。这种心态会让你找不到错误,因为你看到的一切都是正确的。
您从未检查您的流是否打开并且您在ofstream中输入了错误的文件名。
发生的是,您将数据写入文件名farses.dat
,然后尝试打开一个名为frases.dat
的文件(我认为这是正确的名称,它意味着句子)。如果stream::告诉你一个不存在的文件,你正在获取游标位置,它失败了,所以函数返回-1。这是分配缓冲区之前的长度值。当你分配缓冲区时,你会得到一个bad_alloc异常(bad_array_new_length)。
检查文件是否打开,至少可以节省一些调试时间。像这样,
ifstream infile;
infile.open("frases.dat");
if ( infile.is_open() ) {
// File is open, do stuff (...)
if ( length <= 0 ) {
// Empty file / error, don't create buffer!!!
}
// (...)
infile.close();
}
else {
// Couldn't open file
}
编辑:修正错误解释
相关文章:
- 从C++实例化QML
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 如何在c++中为模板函数实例创建快捷方式
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)
- 如何创建一个空的全局类并在启动时实例化它
- 无法创建抽象类的实例
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 我收到以下错误:抛出'std::bad_alloc'实例后终止调用
- 建议在运行时将带有类实例的列表从c++导入qml
- 约束和显式模板实例化
- 通过实例理解std::move及其目的
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- 有没有一种"cleaner"的方法可以在指向基的指针向量中找到派生类的第一个实例?
- 正在生成未知类实例
- 从DLL中删除类的实例
- 在std::vector上存储带有模板的类实例
- 获取错误:在抛出"std::bad::alloc"的实例后终止调用 what(): std::bad_alloc