4

I run commad (Ubuntu 12.04)

cppcheck test.cpp

I am expecting uninitialized variable warning from cppcheck tool. Why cppcheck tool does not print it on the command line?

Example 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
    {//...
    }
}
user12205
  • 2,684
  • 1
  • 20
  • 40
user3455638
  • 569
  • 1
  • 6
  • 17

3 Answers3

10

For information.. if you use --enable=warning, cppcheck writes such message:

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

Daniel Marjamäki
  • 2,907
  • 15
  • 16
7

Because this stuff is hard, and cppcheck is not Almighty God Creator Of The Universe And Knower Of All?

Some issues are actually infeasible to detect in the general case; I'm not sure whether this is one of them. But if cppcheck only examines one translation unit at a time then, well, what if Foo::Foo were defined in some other translation unit?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
4

Static analysis (this is what cppcheck does) is not an exact science, nor can it be. Rice's theorem states: "any nontrivial property of program behavior is undecidable" (see "Understanding Computation:From Simple Machines to Impossible Programs" by Tom Stuart).

Also, check out What is static analysis by Matt Might. In both cases, you should get the idea, that not only is static analysis is hard and in undecidable.

Thus there are any number of reason why ccpcheck fails to report the potential use of an uninitialized variable.

You might get better results, in this case, using valgrind with the tool memcheck which will report uses 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.

thurizas
  • 2,473
  • 1
  • 14
  • 15
  • Don't think Rice's theorem apply here. The program doesn't even have an input! – jinawee Jul 16 '19 at 11:42
  • Rice's theorem talks about non-trivial semantic properties of programs (see https://en.wikipedia.org/wiki/Rice%27s_theorem), while the discussion uses halting on all inputs as an example, semantic properties are not limited to input. – thurizas Jul 16 '19 at 12:30