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

前端 未结 2 1295
后悔当初
后悔当初 2021-02-08 18:04

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

相关标签:
2条回答
  • 2021-02-08 18:34

    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.

    0 讨论(0)
  • 2021-02-08 18:37

    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.

    0 讨论(0)
提交回复
热议问题