Question

I am getting an error about the pointer variable trail current being potentially uninitialized and I am a little confused on why it is happening.

Here is the insert function that I am having an issue with (the error points me to the last if statement)

template <class elemType>
void bSearchTreeType<elemType>::addCustomer(const elemType& insertItem)
{
    binaryTreeNode<elemType> *current;  //pointer to traverse the tree
    binaryTreeNode<elemType> *trailCurrent; //pointer behind current
    binaryTreeNode<elemType> *newNode;  //pointer to create the node

    newNode = new binaryTreeNode<elemType>;
    assert(newNode != NULL);
    newNode->info = insertItem;
    newNode->llink = NULL;
    newNode->rlink = NULL;

    if (root == NULL)
        root = newNode;
    else
    {
        current = root;

        while (current != NULL)
        {
            trailCurrent = current;

            if (current->info == insertItem)
            {
                cerr << "The insert item is already in the list-";
                cerr << "duplicates are not allowed."
                    << insertItem << endl;
                return;
            }
            else if (current->info > insertItem)
                current = current->llink;
            else
                current = current->rlink;
        }//end while

        if (trailCurrent->info > insertItem)
            trailCurrent->llink = newNode;
        else
            trailCurrent->rlink = newNode;
    }
}//end insert
Was it helpful?

Solution

I'm pretty sure this is just the compiler getting confused. Obviously if root is NULL it doesn't go through the else part with while loop at all, and if root is not NULL, then trailCurrent will always be set to something as it must go through the loop at least once.

If it was me, I would just initialize trailCurrent to root (or NULL), once I was sure the warning was not correct.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top