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

前端 未结 2 1296
后悔当初
后悔当初 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  (cout, ", "));
    

    And see what is actually there.

提交回复
热议问题