关于:'std::bad_alloc'实例

regarding: instance of 'std::bad_alloc'

本文关键字:alloc 实例 bad 关于 std      更新时间:2023-10-16

我读了其他的帖子,但是没有一个有帮助。这段代码没有错误,但是有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
}

编辑:修正错误解释