简体   繁体   English

霍夫曼解码循环未迭代

[英]Loop for Huffman decoding not iterating

I am having trouble with my for loop for my c++ class. 我的c ++类的for循环遇到麻烦。 I am reading in from a file that we encoded into binary in a previous part using a huffman tree and now we need to make a decoder. 我正在从使用霍夫曼树在上一部分中编码为二进制文件的文件中读取数据,现在我们需要制作一个解码器。 I am attempting to read in from a file using ifstream::read. 我正在尝试使用ifstream :: read从文件中读取。 Here is my code... 这是我的代码...

ifstream in;
in.open(file_name.c_str());
unsigned char uChars;
in.read((char*) &uChars, 2); //reads in the amount of unique characters
if(in.fail()){
    cout << "Error";
}else{
    int i = (int) uChars;
    int runs;
    for(runs = 0; runs < i; runs++){
        unsigned char rChar;
        unsigned char charFreq;
        in.read((char*) &rChar, 1); //reads in the character
        in.read((char*) &charFreq, 4); //reads in characters frequency
        frequency_table[(int) rChar] = (int) charFreq;
        //frequency_table is declared in constructor
        //unsigned frequency_table[256];
    }
}
in.close();

The read functions and saving the value to the array work perfectly but the problem comes with iterating the variable runs. 读取功能和将值保存到数组的工作都很好,但是问题在于迭代变量运行。 I used gdb to debug and printed out the value of runs each time the loop is ran and I got... 0, 1, 1, 1, 1, 1, 1, 20160 The i in this case is 6 so it should only run 6 times but it is running the loop 7 times and saving a value into my array that shouldn't be there causing my decoder to print out wrong values later. 每次运行循环时,我都使用gdb进行调试并打印出run的值,然后得到... 0,1,1,1,1,1,1,20160在这种情况下,i为6,因此它仅应运行6次,但运行循环7次,然后将不应保存的值保存到我的数组中,导致解码器稍后输出错误的值。 What could be causing my runs variable to not increment as it should? 是什么导致我的runs变量不应该增加?

You have several invalid writes: 您有几次无效的写入:

in.read((char*) &uChars, 2); //reads in the amount of unique characters
in.read((char*) &charFreq, 4); //reads in characters frequency

Either of those could mess up memory; 这些都可能破坏内存; the latter is likely the culprit since it's inside your loop. 后者可能是罪魁祸首,因为它在循环中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM