Search code examples
pvs-studio

PVS-Studio: warning V595 is generated even if pointer is checked


In the following code there is already check for nullptr in (1):

int msg;
struct x * var[2];

if ((var[0] = get_x()) == nullptr) {   // (1)
    return;
}
if (var[0]->data != 11) {              // (2) <<< V595
    msg = 1;
    printf("msg1");
}
if (var[0] && var[0]->data == 12) {    // (3) <<< V595
    msg = 2;
    return;
}

but I still get error: V595. Why?

I agree that there is an exceeding check for nullptr in (3).


Solution

  • Analyzer considers this piece of code abnormal. First, the pointer is being deferenced, and after that it is being verified. Even if it cannot be equal to NULL, it looks very suspicious. There's a possibility that wrong variable is used or checked.

    So it is possible that the wrong variable is used, and the corrected version of code could look like:

    if (FOO->data != 11) {
        msg = 1;
        printf("msg1");
    }
    if (var[0] && var[0]->data == 12) {
        msg = 2;
        return;
    }
    

    Or, probably, the condition is incorrect:

    if (var[0]->data != 11) {
        msg = 1;
        printf("msg1");
    }
    if (FOO && var[0]->data == 12) {
        msg = 2;
        return;
    }
    

    Anyway, the analyzer doesn't like it, and it issues a warning. To eliminate such warnings, remove unnecessary checks which overload the code and confuse other programmers and the analyzer. In this case the analyzer will not issue the warning:

    if ((var[0] = get_x()) == nullptr) {
        return;
    }
    if (var[0]->data != 11) {
        msg = 1;
        printf("msg1");
    }
    if (var[0]->data == 12) {
        msg = 2;
        return;
    }
    

    If you don't want to remove this check, use one of the following ways to suppress warnings: