C++序列化导致段错误

C++ serialization caused segment fault

本文关键字:错误 段错误 序列化 C++      更新时间:2023-10-16

我正在构建一个基于 Huffman 的压缩器,我使用Decoder的序列化来存储将文件解压缩为名为 decoder.bin 的二进制文件所需的信息

main.cpp,它进展顺利

#include "Huffman.hpp"
size_t hash(CodeType cd){
    return cd;
}

int main() {
    /* ------- BUILD -------- */
    .....
    /* ------- ENCODE -------- */
    .....
    /* ------- DECODE -------- */
    Decoder dec(huffmanTree, root);
    std::ofstream ofs("decoder.bin", std::ios::binary);
    ofs.write ((char*)&dec, sizeof(Decoder));
    ofs.close();
    Decoder newDec;
    std::ifstream ifs("decoder.bin", std::ios::binary);
    ifs.read ((char*)&  newDec, sizeof(Decoder));
    ifs.close();
    std::cout << newDec.tree.getCap();
    newDec.restore();
    newDec.decode("encoded.huf", "decoded.txt");
}

但是,如果我使用单独的decode.cpp独立于编码工作的main.cpp来实现解码过程,那么我的机器上会发生奇怪的事情。

>  make -f makeDecoder 
clang++ -c --std=c++11 decode.cpp -o bin/decode.o
clang++ bin/decode.o bin/HTree.o bin/Huffman.o bin/bitsMap.o -o decode
>  ./decode 
1000Restoring ...
Segmentation fault: 11

decode.cpp的所有代码:

#include "Huffman.hpp"
int main() {
    Decoder newDec;
    std::ifstream ifs("decoder.bin", std::ios::binary);
    ifs.read ((char*)&  newDec, sizeof(Decoder));
    ifs.close();
    std::cout << newDec.tree.getCap();
    newDec.restore();
    newDec.decode("encoded.huf", "decoded.txt");
}

(1000是打印容量,忽略它(

所以这很奇怪,相同的代码行为不同,我不知道为什么会发生segment fault

如果您太忙而无法从github下载我的库并构建此程序,则可以忽略此问题,也谢谢。但如果你能:),对我有很大帮助

我的机器信息:

Apple LLVM version 6.0 (clang-600.0.54) (based on LLVM 3.5svn) 
Target: x86_64-apple-darwin14.0.0
Thread model: posix

看起来你有两个主要功能。你在解码器.cpp和main.cpp中有一个,看起来你正在解码器制作文件中构建main。