Reputation: 5649
How to debug uninitialized variables in release mode in C++.
Upvotes: 4
Views: 9023
Reputation: 224089
There's a warning for this. You should try to always compile cleanly at the highest warning level. For VC++ this is level 4. Turn off specific annoying warnings selectively only.
Also, unless you deliberately uncheck the option, VC++ will compile with /RTCu
(or even /RTCsu
) which puts in checks to catch uninitialized variables at run-time.
Of course, proper programming style (introduce variables as late as possible) will prevent such errors from happening in the first place.
Upvotes: 11
Reputation: 10448
Use something like CPPcheck (open-source) or PC-Lint (commercial) to check for them. They will help find a lot of other errors.
Upvotes: 0
Reputation: 20383
I don't know about VC++, but for gcc, there is a warning option -Wuninitialized
that can be used while compiling. Details: http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html
Append: -Wuninitialized
is included in -Wall
, i.e warn all, one of the recommended and most used warning flag. In addition, having -Werror
would fail the compilation whenever any such warning arises.
Upvotes: 2
Reputation: 25497
You need to build release binaries with debug symbols. Here is a reference that may be helpful if you are on Visual Studio.
There must be something analogous for other implementations as well.
Upvotes: 1
Reputation: 9781
Uninitialized variables are a nasty bug to find. Some static checkers would probably be able to find your uninitialized variable. There are open source ones. You might be able to get a trial version of commercial version as well.
Upvotes: 0
Reputation: 6342
If you do not have debugger, you need to add logging statements in your code wherever you want to see the values of variables which you suspect uninitialized.
Sometimes, logging statement may lead to crash if passed an uninitialized pointer. So you can catch the bug there itself in this case.
Upvotes: 0
Reputation: 490158
Generally, rather than debugging uninitialized variables, you want to prevent the very possibility, such as using classes/objects with ctors, so creating one automatically and unavoidably initializes it.
When you do use something like an int
, it should generally be initialized as it's created anyway, so uninitialized variables will be pretty obvious from simple inspection (and you generally want to keep your functions small enough that such inspection is easy).
Finally, most decent compilers can warn you about at least quite a few attempts at using variables without initialization. Clearly such warnings should always be enabled. One important point: these often depend on data-flow analysis that's intended primarily for optimization, so many compilers can/will only issue such warnings when you enable at least some degree of optimization.
Upvotes: 2