I am experiencing a strange error with the constructor for a binary search tree. The project is for an Hoffman Encoding scheme however the issue is whenever i insert more than two items into the STL priority queue, the copy constructor crashes.

void copyTree(myTreeNode* & copy,myTreeNode* originalTree)
		{
			cout<<"Copy tree was just called"<<endl;
			if(originalTree==NULL)
			{
				copy=NULL;
			}
			else
			{
				copy=new myTreeNode();
//the constructor crashes on the third insertion here at this point
				copy->data=originalTree->data;
				copyTree(copy->left, originalTree->left);
				copyTree(copy->right,originalTree->right);
			}
		}
		myTree (const myTree & copy)
		{
			this->root=NULL;
			this->copyTree(this->root, copy.root);
		}



//main
priority_queue<myTree, vector<myTree>, treeCompare> treeQueue;

	map<char, int> occurrenceTracker;
	char character;
	cin>>character;
	occurrenceTracker[character]=1;
	while(cin>>character&&character!='e')
	{
		if(occurrenceTracker.find(character)!=occurrenceTracker.end())
		{
			occurrenceTracker[character]++;

		}
		else
		{
			occurrenceTracker[character]=1;
		}
	}




	map<char,int>::iterator itr;

	for(itr=occurrenceTracker.begin();itr!=occurrenceTracker.end();itr++)
	{
		myTree characterTree;	
		treeNodeClass mapItem(itr->first,itr->second);

		characterTree.insert(mapItem);
		treeQueue.push(characterTree);
	}

I would imagine (since there is not enough code to tell), that the error is due to "originalTree" not being NULL, yet being invalid (either a pointer that has been deleted or a garbage address (uninitialized value)). Make sure that there is no way that either root, left or right pointers can be invalid (i.e. point to nowhere) and still have a non-NULL value. If the problem persists, post more code (like the insert method and the default constructor of myTreeNode).

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