I have the following code below which is part of a program to create a Huffman Coding tree. The problem is that it runs through correctly for one node, outputting that character 'l' for a certain file has a specific frequency. However...after going through several iterations, it runs into a segmentation fault on the line "if(root->isLeaf)" I see the output of "root!=NULL", but then it displays Segmentation Fault.

string encoding;
void FileData::getEncoding(Node *root,string encoding){
		cout << "root!=NULL" << endl;
			cout << "This is a leaf" << endl;
			cout << "Encoding for character '"<< root->value << "' is '" << encoding << "'" << endl;
		cout << "return reached" << endl;
	string encode0;
	cout << "getEncoding for left" << endl;
	string encode1;
	cout << "getEncoding for right" << endl;

Output is as follows:

getEncoding for left
getEncoding for left
This is a leaf
Encoding for character 'l' is '00'
getEncoding for left
getEncoding for left
return reached
getEncoding for right
Segmentation fault

First, using the same name for an argument and a global is confusing (string encoding)...if you are using it as a constant, make sure you initialize it (not all compilers will do this for you, especially in release), and remove the argument from the method declaration and definition.
I don't have everything to debug it, but, this is probably caused by a pointer to memory that is not valid. Pointers may be initialized when they are defined (again, depending on the compiler and optimizations it uses), and are never automatically "reset" to NULL when they are not valid. So the test (root!=NULL) will pass on any pointer, valid or not, that or not initialized to NULL.

This article has been dead for over six months. Start a new discussion instead.