C++ compiler assigns wrong value to unsigned char array in x64,release

  • Thread starter Thread starter HenrikHegelund
  • Start date Start date
H

HenrikHegelund

Guest

On a Windows 7 computer (64 bit) assigning values to unsigned char array does not work correctly in x64, release in Visual studio C++ 2013. It worked well until I installed visual studio 2015, and also work again if I uninstall visual studio 2015 and remove .NET version 4.5.3 and higher (4.6), while .NET 4.5.2 is ok.
On a Windows 10 (64 bit) computer the code is always wrong i Visual Studie C++ 2013 (x64, release) even if visual studio 2015 or .NET 4.5.3 or higher has never been installed.
It is only a problem if the assigned value is 128 or higher and only at some numbers of iterations in the for-loop (e.g. 3 and 6), while others are ok (e.g. 2 and 4).
If optimization is disabled, the code is generated correctly.

Below is some sample code:

// The code below is written in a "Visual C++ CLR Console Application" with all setting as default.
// When compiled in Win32 or in x64,Debug the outcome is "128 = 128" as expected
// When compiled in x64,Release the outcome is "128 = 127" (NOT expected)
// The problem is that even though pic[1] is assigned "128", the value is "127"

#include "stdafx.h"
using namespace System;
int main(array<System::String ^> ^args)
{
unsigned char pic[3];
for (int x = 0; x<3; x++) {
pic[x] = 128;
}
Console::WriteLine(gcnew System::String(pic[0] + " = " + pic[1]));
return 0;
}

// The disassembly looks like this:
// 00000053 mov ecx,7F7F7F80h
// 00000058 lea rax,[rbp-20h]
// 0000005c mov word ptr [rax],cx
// 0000005f mov byte ptr [rax+2],cl
//
// The first line should however have been:
// 00000053 mov ecx,80808080h
// if the code should have been correct.


Continue reading...
 
Back
Top