Why does this code run differently in x64 release and debug?

Viewed 104
#include <iostream>

int binary_search(int (&arr)[6], const int &target) {
    int low = 0;
    int high = sizeof(arr) - 1;

    while (low <= high) {
      int mid = (low + high) / 2;
    if (arr[mid] == target) {
      return mid;
    } else if (arr[mid] > target) {
    high = mid - 1;
    } else if (arr[mid] < target) {
    low = mid + 1;
   }
  }
  return -1;
}

int main() {
   int arr[] = {1, 3, 5, 7, 9, 11};

   std::cout << binary_search(arr, 1) << std::endl;

   return 0;

enter image description here

How can I change it to work correctly

AMD CPU R5 2600

vs2019 + LLVM 12.0.1

enter image description here

Running results:

-1

F:\OpenGL\Source\x64\Debug\DGL.exe (进程 11860)已退出,代码为 0。 要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。 按任意键关闭此窗口. . .

Normal result should be 0

1 Answers

The number of elements in an array is the size of the array divided by the size of one of those elements. So, in your code, to get the index of the last value, you need to include a division by sizeof(int), like so:

    int high = (sizeof(arr)/sizeof(int)) - 1;

As it stands, your code is attempting to access "out-of-bounds" array elements and, as such exhibits undefined behaviour (UB). Such UB is unpredictable and will frequently manifest itself it different ways between different (i.e. Release and Debug) builds.

Furthermore, as you are passing a fixed size array as the first argument, you can just use that (known) size, instead of calculating it:

    int high = 5;

Try adding an extra element to the array initializer in main, like so:

    int arr[] = { 1, 3, 5, 7, 9, 11, 13 };

You will (or should) get an error message, like the following (generated by clang-cl):

error : no matching function for call to 'binary_search'
message : candidate function not viable: no known conversion from 'int [7]' to 'int (&)[6]' for 1st argument
Related