Search code examples
c++code-analysisstatic-code-analysiscppcheck

Why does Cppcheck not find this obvious array out-of-bounds error?


I installed the Cppcheck tool for static code analysis of my C++ project and got the feeling that it performs poorly. For example, can anyone tell me why Cppcheck is unable to find an array out-of-bounds error in the following code?

void f(int c) { 
    char *p = new char[10]; 
    p[c] = 42; 
} 

void g() { 
    f(100); 
} 

There's an online demo where this code can be conveniently checked using Cppcheck. All it comes up with is a memory leak at line 4, no signs of a potential buffer overflow.


Solution

  • Because it is not supported currently.

    This is actually not an obvious error to the compiler. Something like

    char c[5];
    for (int i=0; i<10; ++i)
        c[i] = 0;
    

    is more obvious, as it is all in the same code.

    Something like

    #define f(c) { \
        char *p = new char[10];  \
        p[c] = 42; \
    }
    
    void g() { 
        f(100); 
    } 
    

    is more obvious, because cppcheck and the compiler expand all macros in-place before actual checks.

    However, your posted code is not trivial, because cppcheck as well as the compiler need the whole code inside that function and evaluate it with respect to the parameter. It is of course possible if the function is in sight (it becomes pretty hard, up to impossible, across translation units), but right now, cppcheck does not have that feature.