当函数在fread()应用于局部结构变量后返回时发生访问冲突

Access Violation when function returns after fread() applyed to a local struct variable

本文关键字:返回 变量 访问冲突 结构 函数 fread 应用于局      更新时间:2023-10-16

这是我的程序中的一部分。

void LookUpStuInfo(student stu[], int size, int ID) 
{   
    FILE *fp; 
    if((fp = fopen("stu_dat", "r")) == NULL)
    { 
        cout << "cannot open file" << endl;
        return; 
    } 
    struct student tmp;
    fread(&tmp, sizeof(struct student), 1, fp);
    fclose(fp);
}

stu_dat(由fwrite()创建)存储多个struct student的信息。当此函数结束并返回到main()函数时,将发生访问冲突。

但是,如果在这种情况下我不使用局部结构变量,而是使用学生stu[]并将fread()应用于&stu[0],则效果良好。那怎么了?

好吧,上面的代码足以产生访问冲突。我已经测试过删除LookUpStuInfo()中的所有其他代码,直到只剩下基本的读取和关闭,仍然无法工作。

下面是这个项目的完整代码。如果您想了解有关main()struct student的详细信息,这可能会有所帮助。

#include<iostream>
#include<string>
#include "stdio.h"
#define num 3
using namespace std;
struct student
{
    int ID;
    string name;
    string sex;
    string birthday;
    float score;
};
void SortStuArr(student stu[], int size)
{
    student tmp;
    for (int i = 0; i < size; i++)
        for (int j = (i + 1); j < size; j++)
        {
            if (stu[i].score < stu[j].score)
            {
                tmp = stu[i];
                stu[i] = stu[j];
                stu[j] = tmp;
            }
        }
    cout << "ID" << "    " << "Score" << endl;
    for (int i = 0; i < size; i++)
        cout << stu[i].ID << "t" << stu[i].score << endl;
}
float GetAvgScr(student stu[], int size)
{
    float avg=0;
    for (int i = 0; i < size; i++)
        avg += (stu[i].score);
    avg = avg / size;
    return avg;
}
void LookUpStuInfo(const char* locat, int size, int ID)
{
    FILE *fp;
    if((fp=fopen("stu_dat","r"))==NULL)
    {
        cout << "cannot open file" << endl;
        return;
    }
    struct student tmp;
    for (int i = 0; i < size; i++)
    {
        fread(&tmp, sizeof(struct student), 1, fp);
        if (tmp.ID == ID)
        {
            cout << tmp.name << tmp.ID << tmp.sex << tmp.birthday << tmp.score << endl;
            fclose(fp);
        }
    }
    cout << "Not Found!" << endl;
    fclose(fp);
}
void WritetoFile(student stu[], int size)
{
    FILE *fp;
    if((fp=fopen("stu_dat","w+"))==NULL)
    {
        cout << "cannot open file" << endl;
        return;
    }
    for (int i = 0; i < size; i++)
        fwrite(&stu[i], sizeof(struct student), 1, fp);
    fclose(fp);
}

int main()
{
    student stu[num];
    for (int i = 0; i < num; i++)
    {
        cin >> stu[i].name >> stu[i].ID >> stu[i].sex >> stu[i].birthday >> stu[i].score;
    }
    cout << GetAvgScr(stu, num) << endl;
    WritetoFile(stu, num);
        LookUpStuInfo("stu_dat", num, 1000);
    return 0;
}

我已经测试过删除程序中的所有string,它运行良好。在对string进行操作的函数中,fread()似乎会出错。

您不能像student.name那样将fread写入std::string(或从中写入)。发生崩溃的原因是您有一个损坏的字符串,当编译器试图将其复制到数组中时,结果出现了严重的错误。直接读取数组并没有帮助,因为大概你正计划在某个时候访问数组的成员——在这个时候,一切都会再次消亡。

您需要读取字符串的长度,然后在.

中读取字符串的字符