Why can't cppcheck find an uninitialized variable?

I am running commad (Ubuntu 12.04)

cppcheck test.cpp

      

I am expecting an uninitialized variable warning from the cppcheck tool. Why doesn't the cppcheck tool print it on the command line?

Sample cpp code:

#include <iostream>

class Foo
{
private:
    int m_nValue;

public:
    Foo();
    int GetValue() { return m_nValue; }
};

Foo::Foo()
{
    // Oops, we forget to initialize m_nValue
}

int main()
{
    Foo cFoo;
    if (cFoo.GetValue() > 0)
    {//...
    }
    else
    {//...
    }
}

      

+3


source to share


3 answers


Because it is difficult, and cppcheck is not Almighty God, Creator of the Universe and Knowing everyone?



Some problems are actually impossible to detect in general; I'm not sure if this is one of them. But if cppcheck only checks one translation unit at a time then, well, what if it Foo::Foo

was defined in some other translation unit?

+4


source


For information ... if you use --enable = warning, cppcheck writes a message like this:



[test.cpp: 13]: (warning) The member variable 'Foo :: m_nValue' is not initialized in the constructor.

+7


source


Static analysis (which is what cppcheck does) is not an exact science and it is not. Rice's theorem says: "Any nontrivial property of a program's behavior is undecidable" (see Understanding Computation: From Simple Machines to Impossible Programs by Tom Stewart).

Also, check out What is Matt Might Static Analysis . In both cases, you must understand that not only static analysis is complex and insoluble.

Thus, there are several reasons why ccpcheck does not report the potential use of an uninitialized variable.

In this case, you can get better results using valgrind with the tool's memcheck, which will report the capabilities of potentially uninitialized variables, but being a dynamic tool (versus a static tool) it may give better (or at least different) results.

Hope this help, T.

+3


source







All Articles