Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way find uninitialized member variables

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.

like image 223
user254669 Avatar asked Jan 20 '10 07:01

user254669


People also ask

Where are uninitialized variables stored?

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.

Which is the value of uninitialized the variable?

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.

What is the value of uninitialized variable in C++?

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.

Why are uninitialized variables bad?

"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.


2 Answers

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.

like image 174
Grumbel Avatar answered Sep 30 '22 11:09

Grumbel


cppcheck will find this, e.g.:

cppcheck my_src_dir --output-file=check.txt --inconclusive --enable=warning 
like image 22
Johan Kotlinski Avatar answered Sep 30 '22 09:09

Johan Kotlinski