C++ - 读取二进制文件的段错误

标签 c++ file

我遇到了一个问题,当我尝试读取二进制文件中的 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];

这样你就不必 allocatedeallocate记忆自己。

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

当然,如果练习允许的话,你可以使用 string 相反( string professeur; ),并使用 << 将数据传入和传出和 >> .

关于C++ - 读取二进制文件的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34708513/

相关文章:

c++ - 将 Boost Python 与 Weak Ptr 一起使用?

php - 如何使用 php 将 .xlsx 文件转换为 .xml 文件?

java - BufferedWriter 覆盖现有文件

php - 如何优化这个简单的PHP脚本?

C++:字符串流有什么好处?

c++ - 错误 : imread is not a member of cv

c++ - 如何确保 n 位中至少有 m 位打开?

c++ - 使用 FILE 指针执行文件写入的段错误

c++ - 如何找到 fprintf() 实际错误?

c - 将文本文件拆分为 C 中的单词