Search code examples
cppcheck

Cppcheck does not detect some use-after-free errors?


free.c

#include <stdlib.h>
    
int main() {
    int *ptr = malloc(sizeof(int)); 
    free(ptr);
    *ptr = 0;
}

Running Cppcheck correctly finds the "use-after-free"-error for *ptr = 0;

cppcheck --enable=all free.c

Checking free.c ...
free.c:6:6: error: Dereferencing 'ptr' after it is deallocated / released [deallocuse]
    *ptr = 0;

However, it fails to detect any errors for ptr[0] = 0;

#include <stdlib.h>

int main() {
    int *ptr = malloc(sizeof(int)); 
    free(ptr);
    ptr[0] = 0;
}

Is that considered a bug or limitation in Cppcheck?


Solution

  • Both examples are being detected by the latest version (2.16.x at the time of writing) of Cppcheck.

    input.cpp:6:6: error: Dereferencing 'ptr' after it is deallocated / released [deallocuse]
        *ptr = 0;
         ^
    
    input.cpp:6:5: error: Dereferencing 'ptr' after it is deallocated / released [deallocuse]
        ptr[0] = 0;
        ^
    

    The second example is only detected since Cppcheck 2.11 though. (It was also detected previous to 1.86 but regressed in one of the many major reworkings leading towards 2.0)

    So it seems you might be running an outdated version. Please refer to https://github.com/danmar/cppcheck?tab=readme-ov-file#packages to learn on how to obtain the latest version.