简体   繁体   中英

Loop for Huffman decoding not iterating

I am having trouble with my for loop for my c++ class. 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. 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. What could be causing my runs variable to not increment as it should?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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