当函数在fread()应用于局部结构变量后返回时发生访问冲突
Access Violation when function returns after fread() applyed to a local struct variable
这是我的程序中的一部分。
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
(或从中写入)。发生崩溃的原因是您有一个损坏的字符串,当编译器试图将其复制到数组中时,结果出现了严重的错误。直接读取数组并没有帮助,因为大概你正计划在某个时候访问数组的成员——在这个时候,一切都会再次消亡。
您需要读取字符串的长度,然后在.
相关文章:
- 如何返回变量而不是变量的数值
- 函数,返回变量c++占用的内存位置的大小
- C++中局部变量和返回变量的构造和析构
- 我们如何在范围消失时通过引用返回变量
- 沿枚举 c++ 返回变量类型
- 在 Py_BuildValue 中返回变量字符串
- 递归返回语句无法正确返回变量
- 返回变量为 void (*)(void)
- 地址运算符是否返回变量引用的对象的地址
- 从函数返回变量地址时如何修复"与局部变量关联的堆栈内存地址"?
- 如何访问Python中编译的多个返回变量
- Binary_search通过其成员函数的返回变量[C ]找到类对象
- C++函数中声明和返回变量,并在主函数中使用它
- 从 C++ 返回对对象的引用时,是否需要在返回变量中使用 "&" 运算符?
- 函数返回看似随机的数字,而不是返回变量的值
- 从函数返回变量的链表
- 通过函数参数中的引用返回变量
- C++动态内存分配.将动态分配的 char* 返回变量数组分配给 char 变量
- 传递或返回变量时并不总是调用复制构造函数
- 尝试在模板 c++ 中返回变量时出错