首页 > 解决方案 > C++ 错误:在抛出 'std::bad_alloc' 的实例后终止调用

问题描述

我创建了一个用户定义的 String 类和一些文件处理函数。我之前尝试在 ubuntu 上使用 g++ 编译这段代码和 gdb 调试几次。错误被抛出

s2.diskIn(iflile);

界面:

class String {
    long unsigned int len; 
    char *cStr;
public:
    String(const String &);
    explicit String(const char * const = NULL);

    void diskIn(std::ifstream &);
    void diskOut(std::ofstream &);
    const char *getString();
    String operator = (const String);
    ~String();
};

复制构造函数

String::String(const String &ss) {
    if (ss.cStr == NULL) {
        cStr = NULL; len = 0;
    } else {
        len = ss.len;
        cStr = new char[len + 1];
        strcpy(cStr, ss.cStr);
    }
}

默认/赋值构造函数

String::String(const char * const p) {
    if (p == NULL) {
        cStr = NULL; len = 0;
    } else {
        len = strlen(p);
        cStr = new char[len + 1];
        strcpy(cStr, p);
    }
}

错误函数:

void String::diskIn(std::ifstream &fin) {
    String temp;
    fin.read((char *)&temp.len, sizeof(int));
    temp.cStr = new char[len + 1];
    int i;
    for (i = 0; i < temp.len; i++) 
        fin.get(temp.cStr[i]);
    temp.cStr[i] = '\0';
    *this = temp;   
}

复制赋值运算符

String String::operator = (const String ss) {
    if (cStr != NULL) {
        delete[] cStr;
        cStr = NULL;
        len = 0;
    }

    if (ss.cStr != 0) {
        len = ss.len;
        cStr = new char[len + 1];
        strcpy(cStr, ss.cStr);
    }
    return *this;
}

析构函数

String::~String() {
    delete[] cStr;
}
int main() {
    String s2;
    std::ifstream ifile("document.txt");

    s2.diskIn(ifile); //Error was thrown here
    std::cout << s2.getString() << "\n";
    ifile.close();

    return EXIT_SUCCESS;
}

标签: c++oopubuntusigabrt

解决方案


推荐阅读