Menu ▾ ▴

False positive nullPointer when a NULL argument is paired with a non-NULL &x argument

cstratak
2026-11-12
2026-11-12
  • cstratak

    cstratak - 2026-11-12

    I've been investigating some results of analysis for lxml from openscanhub in Fedora (which uses cppcheck) that seemed false positives and drove me down the cppcheck rabbit hole. I've drafted a simple reproducer that mirrors the generated Cython code that is sprouted from python-lxml and used claude to try to analyze the cause.

    The issue is a possible null pointer dereference on a line that can never run with a NULL pointer.

    void f(int *a, int *b) {
        if (a)
            *a = 0;
        else
            *b = 0;
    }
    void g(void) {
        int x;
        f(&x, 0);
    }
    

    Output of cppcheck test.c (2.22.0):

    test.c:5:10: warning: Possible null pointer dereference: b [nullPointer]
    test.c:9:11: note: Calling function 'f', 2nd argument '0' value is 0
    

    Here f() is only called once, with a = &x and b = NULL. &x is never NULL, so if (a) is true for that call and *b = 0 is never reached.

    It seems cppcheck uses the values from the call (a = &x, b = 0), but does not use the value of a when evaluating if (a). Calling f((int *)8, 0) gives no warning, so the problem seems specific to address-of values.

    Cython generates this pattern in every extension module that loops over a dict. Its helper __Pyx_dict_iter_next(..., PyObject **pkey, PyObject **pvalue, PyObject **pitem, ...) is called with &key, NULL, NULL for a loop over keys, and ends with:

    if (pitem) {
        *pitem = next_item;
    } else if (pkey && pvalue) {
        ...
    } else if (pkey) {
        *pkey = next_item;
    } else {
        *pvalue = next_item;   /* Possible null pointer dereference: pvalue */
    }
    

    2.21.1 reports this for Cython-built modules. With the 2.22.0 update the issue is no longer reported, but only as a side effect of bcd74c73: the helper has an earlier if (...) { return ...; } else ..., and since that commit, cppcheck stops following the NULL after such a branch. The example above has no early return and still warns in 2.22.0.

    Reproduced with 2.21.1 and 2.22.0, for both C and C++.

    I'm providing a patch with the fix that was generated by the opus 5.5 model, if it's any help, but I don't understand the code well enough to verify its correctness., however all the test cases pass with it and the issue is resolved.

     

Log in to post a comment.