Easy way find uninitialized member variables
If you use GCC you can use the -Weffc++
flag, which generates a warnings when a variable isn't initialized in the member initialisation list. This:
class Foo
{
int v;
Foo() {}
};
Leads to:
$ g++ -c -Weffc++ foo.cpp -o foo.o
foo.cpp: In constructor ‘Foo::Foo()’:
foo.cpp:4: warning: ‘Foo::v’ should be initialized in the member initialization list
One downside is that -Weffc++
will also warn you when a variable has a proper default constructor and initialisation thus wouldn't be necessary. It will also warn you when you initialize a variable in the constructor, but not in the member initialisation list. And it warns on many other C++ style issues, such as missing copy-constructors, so you might need to clean up your code a bit when you want to use -Weffc++
on a regular basis.
There is also a bug that causes it to always give you a warning when using anonymous unions, which you currently can't work around other then switching off the warning, which can be done with:
#pragma GCC diagnostic ignored "-Weffc++"
Overall however I have found -Weffc++
to be incredible useful in catching lots of common C++ mistakes.
cppcheck will find this, e.g.:
cppcheck my_src_dir --output-file=check.txt --inconclusive --enable=warning
Valgrind (FREE, on Linux) and Purify (on Windows) find un-initialized variables, invalid pointers and such by running your code in a special virtual machine.
This is easy to use and extremely powerful; it will likely find many bugs beyond the obvious un-initialized variables.
Coverity, Klocwork and Lint can find un-initialized variables using static code analysis.