Burgan
Burgan

Reputation: 900

Incorrect warning in Xcode?

The following code has a warning on the indicated line in Xcode.
Is this warning actually valid though?
If this is a valid warning how is that so?
If this warning is incorrect, what caused Xcode to create a warning on this line?

EDIT: Also, why is there no warning when prevPtr is referenced inside the while loop above the line where the warning occurs?

The warning reads variable 'prevPtr' may be uninitialized when used here
It is on the line prevPtr->next = delPtr->next

I believe that it is impossible to reach this line without the variable being initialized. Which would make this warning pointless.

void myEditor::deleteLine(int num)
{
    Line *delPtr = head;

    if (delPtr == NULL) {
        return;
    }

    if (head->linenum == num) {
        head = head->next;
    }
    else {
        Line *prevPtr;

        while (delPtr != NULL && delPtr->linenum != num) {
            prevPtr = delPtr;
            delPtr = delPtr->next;
        }

        if (delPtr == NULL) {
            cout << "Line " << num << " does not exist." << endl;
        }
        else {
            prevPtr->next = delPtr->next; // warning appears here
        }
    }

    delete delPtr;
}

Upvotes: 0

Views: 91

Answers (1)

user149341
user149341

Reputation:

If you use the "Product > Analyze" menu item in Xcode, it'll show you much more details on this type of warning. Here's the results I got when I tried (after making some assumptions about the definition of Line):

1. 'prevPtr' initialize to a null pointer value; 2. Loop body executed 0 times; 3. Access to field 'next' results in a dereference of a null pointer (loaded from variable 'prevPtr')

In this case, this appears to be a failure of the analysis: the compiler is not recognizing that, for the while loop to run zero times, either delPtr == NULL (which would have caused an early return), or delPtr->lineNum == num, implying head->lineNum == num (which would have caused the else block to not be run).

That being said, it's not clear to a reader that this code is correct. Restructuring your code to avoid this warning would be advisable.


With regard to the question you added in an edit ("Why is there no warning when prevPtr is referenced inside the while loop"): prevPtr is only assigned to in the loop. It is not dereferenced, so this is not an error.

Upvotes: 3

Related Questions