C++ - 分段故障读取二进制文件

Rem*_*rtz 5 c++ file

我遇到了一个问题,当我尝试读取 char* professeur二进制文件时它失败了,在read()函数中给我一个分段错误.奇怪的是,对于load其他类中的所有其他函数来说,读取char*成员的工作正常但是对于这一个,即使professeur在我得到一个seg错误中正确写入.

所以这是代码:

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&);
};
Run Code Online (Sandbox Code Playgroud)

Cours.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);
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*_ds 3

n应检查以确保它不会大于缓冲区。

save()

int n=strlen(professeur);
Run Code Online (Sandbox Code Playgroud)

n此处最大应为 59 - 需要检查。

load()

i.read((char *)&n, sizeof(int));
Run Code Online (Sandbox Code Playgroud)

最好n也检查一下这里(最多 59)。

还:

int n=strlen(professeur);
char buff[60], *buff2;

o.write((char *)&n, sizeof(int));
strcpy(buff, getProfesseur());
o.write(buff, n+1);
Run Code Online (Sandbox Code Playgroud)

使用两个不同的值来写入数据:strlen(professeur)和 然后getProfesseur()

您也不分配内存professeur(至少不在显示的代码中)。所以strcpy(professeur, buff);inload()也会失败。

你不妨改变一下:

private:
    char* professeur;
Run Code Online (Sandbox Code Playgroud)

private:
    char professeur[60];
Run Code Online (Sandbox Code Playgroud)

这样你就不必自己allocate记忆deallocate

并确保所有字符串都以空结尾。

当然,如果练习允许,您可以改用string( ),并使用和string professeur;流式传输数据。<<>>