I am trying to write a program to simulate Huffman encoding and decoding. In order to do so, I needed to serialize a binary tree in a text file, so that I could read it again later and reconstruct the tree (when decoding the huffman file).
However, after my function (readBinaryTree) that reads the file (which is recursive), the program just stops executing. I've never seen this before.
Here's the code:
if (!decode) {
.
.
.
//alot of stuff here
.
.
.
}
else if (decode) {
std::ifstream keyFile("hufftreekey.txt");
Node* HuffTree = NULL;
std::cout << "PRE!" << std::endl;
readBinaryTree(HuffTree, keyFile); //THIS FUNCTION EXECUTES, BUT NOTHING AFTER IT DOES
std::cout << "POST!" << std::endl;
std::map<char, std::string> codes = buildCodes(HuffTree);
std::ofstream outFile;
outFile.open ("mobydick_decoded.txt.huff");
char c;
std::ifstream input( argv[ 1 ] );
while (input >> std::noskipws >> c) {
if (codes.find(c) != codes.end()) {
std::string huffcode = codes[c];
outFile << huffcode;
}
else{
std::cout << "ERROR!" << std::endl;
}
}
outFile.close();
}
Output in terminal is "PRE!", but it never prints "POST!". I don't get any error message, no exceptions are thrown, it just never prints, and nothing after the function is called is executed.
This is the function:
void readBinaryTree(Node* root, std::ifstream &fin){
std::string s_val;
char val;
std::getline(fin, s_val);
val = s_val[0];
if(val == '#')
return;
else if(val == '_') {
root = new Node();
if (root == NULL) {
std::cout << "MEMORY ALLOC FAILURE!" << std::endl;
}
root->content = '_';
readBinaryTree(root->leftChild, fin);
readBinaryTree(root->rightChild, fin);
}
else {
root = new Node();
if (root == NULL) {
std::cout << "MEMORY ALLOC FAILURE!" << std::endl;
}
root->content = val;
readBinaryTree(root->leftChild, fin);
readBinaryTree(root->rightChild, fin);
}
}
This is not an infinite loop problem, the program finishes but it just seems to skip everything after the readBinaryTree function is called
You're not building a binary tree. You're leaking memory like a sieve leaks rain-water, then executing undefined behavior to add insult to injury.
Change this:
void readBinaryTree(Node* root, std::ifstream &fin)
to this:
void readBinaryTree(Node*& root, std::ifstream &fin)
// see addition here ====^
Try passing that pointer by reference (or address) and see what happens.