53

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.

Laurel
  • 5,965
  • 14
  • 31
  • 57
user254669
  • 531
  • 1
  • 4
  • 3
  • Good article "In search of uninitialized class members" - http://www.viva64.com/en/b/0354/ –  Oct 29 '15 at 14:38
  • In case of using clang compiler you can try memory sanitizer: http://clang.llvm.org/docs/MemorySanitizer.html. It perform dynamic checking and has significantly less overhead compared to valgrind. There is nice presentation from the author on cppcon2014 https://www.youtube.com/watch?v=V2_80g0eOMc – Jurasic Feb 02 '16 at 15:24

11 Answers11

32

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.

Grumbel
  • 6,585
  • 6
  • 39
  • 50
11

cppcheck will find this, e.g.:

cppcheck my_src_dir --output-file=check.txt --inconclusive --enable=warning
VinGarcia
  • 1,015
  • 12
  • 19
Johan Kotlinski
  • 25,185
  • 9
  • 78
  • 101
  • 1
    Probably because cppcheck is not that smart. It will warn against not initializing in the constructor, but it most often cannot examine complicated paths where e.g setters in constructors initialize a member. – Benjamin Bannier Dec 15 '11 at 19:03
  • 1
    Cppcheck has been improved since then, version 1.75 is able to detect only partial struct initializations. But of course some cases like [this one](http://stackoverflow.com/q/38829964/2932052) are still too hard for it, though also hard for humans (as I observed). – Wolf Sep 05 '16 at 08:17
  • It still doesn't understand delegating constructors. – juzzlin May 14 '19 at 12:05
10

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.

George Hilliard
  • 15,402
  • 9
  • 58
  • 96
Will
  • 73,905
  • 40
  • 169
  • 246
  • *"Easy to use"* is subjective. With a GCC extended assembly block, all we get is a line number pointing to the end of the block (the closing paren), and not the actual variable causing the problem. That's even with `--track-origins`. – jww Aug 17 '15 at 15:54
  • @jww this is a gcc problem (not producing enough debug info), not a valgrind problem. It might go away if you compile your source with -ggdb or something, but I'd be surprised. I'm working in llvm backends and its much the same situation there. – Will Aug 18 '15 at 05:20
  • It seems that purify is no longer a a good option: http://marlowa.blogspot.com.br/2015/08/the-death-of-purify.html – VinGarcia Jan 30 '18 at 01:13
9

Valgrind can tell you if you are on linux.

Zitrax
  • 19,036
  • 20
  • 88
  • 110
7

-Wuninitialized ?

(This only checks if a variable is used uninitialized, i.e. if

struct Q { 
  int x, y;
  Q() : x(2) {}
  int get_xy() const { return x*y; }
};

g++ will warn only when the user calls get_xy() without assigning to y.)

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • 2
    Also requires -O1 or above, which isn't the default. –  Jan 20 '10 at 07:59
  • I am unable to get g++ 4.3.3 to warn for data members with -Wuninitialized, are you sure it works here? (Simple test: add `int main() { return Q().get_xy(); }` to your code.) –  Jan 20 '10 at 08:02
  • @Roger-plate: Unfortunately you need to use `int main() { Q q; return q.get_xy(); }` to work. – kennytm Jan 20 '10 at 15:23
5

Visual Studio (MSVC) has a /sdl (Enable Additional Security Checks) compiler option (http://msdn.microsoft.com/en-us/library/jj161081.aspx). At run-time, it:

Performs class member initialization. Automatically initializes class members of pointer type to zero on object instantiation (before the constructor runs). This helps to prevent use of uninitialized data associated with class members that the constructor does not explicitly initialize.

This will not help you detect uninitialized member variables at compile-time, but it makes the behaviour more predictable when it happens at run-time. You shouldn't write code that relies on this option being enabled though, of course.

Quatari
  • 59
  • 1
  • 1
4

If you're using Visual Studio, you could compile in debug mode, stop the program in the debugger and look for which variables are initialised to bytes containing 0xCC (stack) or 0xCD (heap).

Though personally, I'd invest in a static analysis tool for a more thorough approach.

Kaz Dragon
  • 6,681
  • 2
  • 36
  • 45
2

/analyze on Visual Studio ("Team System")

Terry Mahaffey
  • 11,775
  • 1
  • 35
  • 44
  • 3
    Are you sure this works for uninitialized *member* variables? In our tests, it only finds uninitialized local variables. – Agentlien Mar 12 '13 at 14:43
0

Beware! Compiler options proposed here are neither reliable, nor version-independent. Consider the simple example:

class A {
  int a;
public:
  void mA() {
    printf("haha");
    ++a;
    int g = 2/a;
    printf("%i\n",g);
  }
};

int main() {
  A a;
  a.mA();
}

Compiled with g++ -O3 -Weffc++ -Wuninitialized this thing reports uninitialized on gcc versions up to 4.6 inclusive, and passess happily on 4.7 and 4.8 (tested on MacPorts). Then, curiously, if we remove the printf("haha");, both 4.7 and 4.8 suddenly see uninitialized A::a. Clang is a little better, since it somehow assigns rubbish (instead of convenient 0) to uninitialized vars, so you see their disastrous effect easier/sooner.

I didn't have much luck in spotting the above uninitialized A::a with valgrind either; maybe the gentlement suggesting valgrind could provide appropriate options to spot this error.

Bottom line: great question, not much reliable solutions at the moment... (the way I see it).

P Marecki
  • 1,108
  • 15
  • 19
  • 2
    With any optimization level above `-O0`, gcc 4.7 optimizes out everything except the calls to `printf`. I checked the assembly code and it's just two calls to `printf`. So gcc's compile-time evaluation is not detecting the uninitialized value. And `valgrind` has no chance to detect it at runtime since it's only two calls to printf with constant arguments. – Colin D Bennett Oct 07 '14 at 22:06
0

Clang with clang-analyze is able to do this. It will event create a nice HTML report that indicates when the unused variable is accessed.

Jean-Michaël Celerier
  • 7,412
  • 3
  • 54
  • 75
-2

Consider the following code

unint.cpp:

int main()
{
    int a;
    int b;
    a++;
    b = b + 5;

    return 0;
}

If the code is compiled with following comment, the warning messages shall be displayed.

g++ -O3 -Wuninitialized unint.cpp

Note: the -Wuninitialized needs the -O3 option also.

  • The output:unint.cpp: In function 'int main()': unint.cpp:8: warning: 'a' is used uninitialized in this function unint.cpp:9: warning: 'b' is used uninitialized in this function – Tamilalagan Apr 25 '13 at 11:02
  • The question is titled "Easy way [to] find uninitialized **member** variables". These are not member variables. We all know about `-Wunitialized` for non-member variables, and we should all have it already as part of already using `-Wall -Wextra -Wpedantic`. Also, it does not "need the -O3 option" or any other form of optimisation to be present or absent, although they may affect which warnings are returned if optimisation causes side-effect-less variables to be removed. – underscore_d Aug 12 '16 at 11:39