dimanche 18 septembre 2016

Unexpected compound 'if' statement behavior

I've been programming in C++ for a while, but came across an unexpected issue today when debugging a Linux program. Let me provide code to explain:

class ClassA
{
public:
    ClassA ()
    {
        strB = strdup("Hello");
    }

    char* strB;
};

int main()
{
    ClassA a = new ClassA();

    a = NULL;

    if (a == NULL || a->strB == NULL)   // <===== Problem line
        return 1;
}

Focusing on the line with the 'if' statement, I've always been under the impression that if the first condition is true, any further condition tests with the || (OR) operator are immediately skipped and the code following the if statement is executed.

Today I ran into a segfault in an 'if' statement almost exactly like the one above. 'a' was NULL but instead of returning -1, the program instead went on to test the next condition, which caused a segfault because 'a' was NULL.

Have I been misunderstanding how multiple condition testing works in C++ all this time?

Thank you in advance.

Aucun commentaire:

Enregistrer un commentaire