引发异常:读取访问冲突。 _Pnext为0xCDDC8C

时间:2019-12-23 15:11:44

标签: c++

我正在尝试学习C ++中的归档,但遇到一个非常奇怪的错误。如果我在类或结构中使用字符串,则从文件加载后它们会很好地输出,但是如果程序结束或调用了某些其他函数,则会引发异常。 这是我的代码

    #include <iostream>
    #include <string>
    #include <fstream>
using namespace std;
class Student {
    string name;
    int reg, marks;
public:
    void newDB();
    void outDB();
};
void Student::newDB() {
    cout << "\nWHAT IS NAME\t";
    cin >> name;
    cout << "\nWHAT IS REG #\t";
    cin >> reg;
    cout << "WHAT IS MARKS\n";
    cin >> marks;
}
void Student::outDB()
{
    cout << "\n------------------------------------\n"
        << "NAME IS \t" << name << endl
        << "REG # IS\t" << reg << endl
        << "MARKS IS\t" << marks << endl;
}
void saveData(Student classOOP[], int nn)
{
    ofstream outFile;
    if (!outFile)
    {
        cout << "FILE NOT LOADED\n";
        exit(-1);
    }
    outFile.open("std.DAT", ios::app | ios::binary);
    outFile.write(reinterpret_cast<char*>(&nn), sizeof(nn));
    outFile.write(reinterpret_cast<char*>(classOOP),nn*sizeof(Student));
    outFile.close();
}
void loadData(Student classOOP[], int& nn)
{
    ifstream outFile;
    if (!outFile)
    {
        cout << "FILE NOT LOADED\n";
        exit(-1);
    }
    outFile.open("std.DAT", ios::app | ios::binary);
    outFile.read(reinterpret_cast<char*>(&nn), sizeof(nn));
    outFile.read(reinterpret_cast<char*>(classOOP), nn * sizeof(Student));
    outFile.close();
}
int main()
{

    Student classOOP[35];
    int nOs=0;
    int choice, check;
    do {
        cout << "TYPE 1 for input\n2 for output\n3 for load data\n4 for save data\n";
        cin >> choice;
        switch (choice)
        {
        case 1:
            cout << "How many Students are in CLASS\n";
            cin >> nOs;
            for (int i = 0; i < nOs; i++)
            {
                cout << "\nDATA OF STUDENT # \t" << i + 1<<endl;
                classOOP[i].newDB();
            }
            break;
        case 2:
            for (int i = 0; i < nOs; i++)
            {
                cout << "\nDATA OF STUDENT # \t" << i + 1<<endl;
                classOOP[i].outDB();
            }
            break;
        case 3:
            saveData(classOOP , nOs);
            break;
        case 4:
            loadData(classOOP, nOs);
        default:
            break;
        }
    } while (choice != 5);
}

错误是

Exception thrown: read access violation.
_Pnext was 0xCDDC8C.

当抛出名称为xmemory的异常并且此时已经出现异常时,将打开新文件

for (auto _Pnext = &_Myproxy->_Myfirstiter; *_Pnext; *_Pnext = (*_Pnext)->_Mynextiter) {
        (*_Pnext)->_Myproxy = nullptr;
    }

0 个答案:

没有答案