我遇到了一个问题,当我尝试读取二进制文件中的 char* professeur
时失败了,在 read()
函数中出现了段错误。奇怪的是,对于其他类中的所有其他 load
函数来说,读取 char*
成员工作得很好,但对于这个,即使 professeur
在 I got a seg fault 中正确写入。
代码如下:
Cours.h
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;
#include "Liste.h"
#include "Event.h"
#include "Professeur.h"
class Cours: public Event
{
private:
char* professeur;
Liste<int> groupes;
public:
void save(ofstream&) const;
void load(ifstream&);
};
类(class).cpp
void Cours::save(ofstream& o) const
{
int n=strlen(professeur);
char buff[60], *buff2;
o.write((char *)&n, sizeof(int));
strcpy(buff, getProfesseur());
o.write(buff, n+1);
groupes.save(o);
Event::save(o);
}
void Cours::load(ifstream& i)
{
int n;
char buff[60];
i.read((char *)&n, sizeof(int));
cout<<"n: "<<n<<endl;
if(i.read(buff, n+1))//seg fault
{
strcpy(professeur, buff);
cout<<"prof: "<<professeur<<endl;
}
else
cout<<"erreur read prof cours"<<endl;
groupes.load(i);
Event::load(i);
}
最佳答案
n
应该检查以确保它不会大于缓冲区。
在save()
:
int n=strlen(professeur);
n
此处最多应为 59 - 需要检查。
在load()
:
i.read((char *)&n, sizeof(int));
最好检查一下n
这里也是(最多 59 个)。
还有:
int n=strlen(professeur);
char buff[60], *buff2;
o.write((char *)&n, sizeof(int));
strcpy(buff, getProfesseur());
o.write(buff, n+1);
两个不同的值用于写入数据:strlen(professeur)
然后 getProfesseur()
.
您也没有为 professeur
分配内存(至少不在显示的代码中)。所以strcpy(professeur, buff);
在 load()
也会失败。
你不妨改变:
private:
char* professeur;
到
private:
char professeur[60];
这样你就不必 allocate
和 deallocate
记忆自己。
并确保所有字符串都以 null 结尾。
当然,如果练习允许的话,你可以使用 string
相反( string professeur;
),并使用 <<
将数据传入和传出和 >>
.
关于C++ - 读取二进制文件的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34708513/