C ++错误:抛出“ std :: bad_alloc”实例后终止调用

时间:2019-07-06 14:23:09

标签: c++ oop ubuntu sigabrt

我创建了一个用户定义的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;
}

0 个答案:

没有答案