Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to debug a variable that is optimized away in Release build

I am using VS2010. My debug version works fine however my Release version kept on crashing. So In the release version mode I right clicked the project chose Debug and then chose start new instance. At this point I saw that an array that I had declared as such

int ma[4]= { 1,2,8,4};

Never gets initialized. Any suggestions on what might be going on.

like image 254
MistyD Avatar asked Jun 25 '13 14:06

MistyD


2 Answers

When you build in Release, the compiler performs many optimizations on your code. Many of the optimizations include replacing variables with hard-coded values, when it is possible and correct to do so. For example, if you have something like:

int n = 42;
cout << "The answer is: " << n;

By the time the optimizer gets done with it, it will often look more like:

cout << "The answer is: " <<  42;

...and the variable n is eliminated from your program completely. If you are stepping through a release version of this program and trying to examine the value of n, you may see very odd values or the debugger may report that n doesn't exist at all.

There are many other optimizations that can be applied which make debugging an optimized program quite difficult. Placing a breakpoint after the initialization of an array could yield very misleading information if the array was eliminated, or if the initialization of it was moved to someplace else.

Another common optimization is to eliminate unused variables, such as with:

int a = ma[0];

If there is no code in your program which actually uses a, the compiler will see that a is unneeded, and optimize it away so that it no longer exists.

In order to see the values that ma has been initialized with, the simplest somewhat reliable approach is to use so-called sprintf debugging:

cout << "ma values: ";
copy (ma, ma+4, ostream_iterator <int> (cout, ", "));

And see what is actually there.

like image 179
John Dibling Avatar answered Sep 23 '22 13:09

John Dibling


If you debug release build the debugger will report bogus values or will not be able to display any values for most of your variables. The safest way to check that the value of a variable is in Release build is to use logging.

So most probably your array is initialized in Release just as in Debug build but you are not able to see that through the debugger. It seems you have some other problem that is causing the code to crash in Release. Look for some other uninitialized variable or some stack corruption/index out of bounds access.

like image 36
Ivaylo Strandjev Avatar answered Sep 20 '22 13:09

Ivaylo Strandjev