I’m trying to serialize my huffman tree to a file, but having issue with the recursive nature of the problem. I have no trouble printing it to console using cout, but I get segmentation fault when I try to store it in a string or write to a file.
string putData(Node *n, string &s) {
if (n->leaf()) {
s << "[" << n->value() << "]";
} else {
s << ".";
}
if (n->left())
putData(n->left(), s);
if (n->right())
putData(n->right(), s);
}
It’s the same issue with an ofstream object. Actually, after the program segfaults, I check the file and its contents are proper. But why is it segfaulting at the end? How do I stop the program from segfaulting?
string putData(Node *n, ofstream &s) {
s.open("huffout.txt", ios::app);
if (n->leaf()) {
s << "[" << n->value() << "]";
} else {
s << ".";
}
s.close()
if (n->left())
putData(n->left(), s);
if (n->right())
putData(n->right(), s);
}
Your function is declared to return
stringbut has no return statement, if anything looks at the return value that could cause a segfault. Your compiler should have warned you about the missing return, aren’t you compiling with warnings?Also, the first code example uses a
stringbut tries to append to it withoperator<<, presumably that’s just a copy’n’paste error.