[英]C++ - segmentation fault reading binary file
我遇到一个问题,当我尝试在二进制文件中读取char* professeur
,它失败,从而在read()
函数中出现了段错误。 奇怪的是,对于其他类中的所有其他load
函数而言,读取char*
成员都很好,但是对于这一类,即使professeur
是正确编写的,也遇到了seg错误。
所以这是代码:
库尔斯
#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&);
};
库尔斯
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;
),并使用<<
和>>
<<
和传出数据。
首先,您读取名称的长度。 分配给名称的allocat char
的长度为/0
长+1。 从文件读取到目标,并在末尾附加\\0
:
void Cours::load(ifstream& i)
{
int n;
i.read((char *)&n, sizeof(int));
cout<<"n: "<<n<<endl;
if ( n <= 0 )
return;
professeur = new char[n+1]; // allocate professeur
if ( i.read( professeur, n ) ) // read directly to professeur
{
professeur[ n ] = ´\0`; // write \0 at end of name
cout<<"prof: "<<professeur<<endl;
}
else
{
delete [] professeur;
professeur = nullptr;
cout<<"erreur read prof cours"<<endl;
}
groupes.load(i);
Event::load(i);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.