Registered: 13 years ago
There's a memory leak bug in the Insert function of the bSearchTreeType template class defined in Malik on pp657-658.
The bug surfaces when you want to insert a duplicate value. If you follow the programme flow, the first thing the function does is to allocate memory for a new node.
If it finds that there already exists a node with the same value, it prints an error message and then exits the function. What happens to the newly allocated node? Well, the pointer to it is destroyed but not the node itself. It just hangs around in memory and can never be used again - without a pointer to tell you where it is, you can't access it. Hence the memory leak.
To fix the bug, just change the error checking part to:
if (current->info == insertItem)
cerr<<"The insert item is already in the list - ";
cerr<<"duplicates are not allowed."<<endl;
delete newNode; // deallocate the memoryreturn;