The debug mode and the release mode are different. Why?

Asked 2 years ago, Updated 2 years ago, 113 views

The chords are weird. Visual Studio 2008 is developing it, but why will it be different when it is debugged and released?

int _tmain(int argc, _TCHAR* argv[])
{

    for( int i = 0; i < 17; i++ ) 
    { 
        int result = i * 16;

        if( result > 255 )
        {
            result = 255;
        }

        printf("i:%2d, result = %3d\n", i, result) ; 
    } 

    return 0;
}

It's working as I expected in debug mode.

i: 0, result =   0
i: 1, result =  16
(...)
i:14, result = 224
i:15, result = 240
i:16, result = 255

But in the release mode, the output is weird when it's i:15.

i: 0, result =   0
i: 1, result =  16
(...)
i:14, result = 224
i:15, result = 255
i:16, result = 255

Why is this the only way to get the correct answer when you select "Optimization -> Not to optimize" in release mode?

c c++ optimization visual-studio-2008 compiler-bug

2022-09-22 14:46

1 Answers

Oh, I've tried it, and in VC 2008 and 2010, debugs and releases are different It's the same on VC2012.

The command you wrote when compiling is cl/Ox vc15-bug.cpp/Fasc.

The reason why there are different results in each situation is because This is because the for statement does not check the value of i*16 when checking the conditions, but instead writes the count and the compiler incorrectly counts. But I don't know why the compiler made the count weird.

; 6    :    for( int i = 0; i < 17; i++ ) 

  00001 33 f6        xor     esi, esi
$LL4@main:
  00003 8b c6        mov     eax, esi
  00005 c1 e0 04     shl     eax, 4

; 7    :    { 
; ; 8    :        int result = i * 16;
; 9    : 
; ; 10   :        if( result > 255 )

  // The original esi, 14 should be 15, not 14
  00008 83 fe 0e     cmp     esi, 14            ; 0000000eH
  0000b 7e 05        jle     SHORT $LN1@main

; 11   :        {
; ; 12   :            result = 255;

  0000d b8 ff 00 00 00   mov     eax, 255       ; 000000ffH
$LN1@main:

; 13   :        }


2022-09-22 14:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.