I am looking for an easy way to find uninitialized class member variables.
Finding them in either runtime or compile time is OK.
Currently I have a breakpoint in the class constructor and examine the member variables one by one.
uninitialized data starts at the end of the data segment and contains all global variables and static variables that are initialized to zero or do not have explicit initialization in source code. For instance, a variable declared static int i; would be contained in the BSS segment.
INTRODUCTION: An uninitialized variable has an undefined value, often corresponding to the data that was already in the particular memory location that the variable is using.
The value in an uninitialized variable can be anything – it is unpredictable, and may be different every time the program is run. Reading the value of an uninitialized variable is undefined behaviour – which is always a bad idea. It has to be initialized with a value before you can use it.
"Uninitialized variables contain some value" is a incorrect statement which unfortunately is teached. A program who access an uninitialized variable has Undefined Behavior, which means it can have any behavior.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With