Erroneous output of a C++ program in MacOS that gives correct output on Windows PC

Hello. I have a M1 Mac mini with MacOS 12.1 (MacOS Monterey).

I have written a C++ program in the inbuilt vim text editor for sorting an Array of integers in ascending order using Merge Sort Algorithm. The compiler I am using is the official Clang compiler. MI tried the g++ command as well as clang++ command to compile the program. (Actually both the commands run clang compiler only)

The weird thing I am facing is that sometimes it replaces some integers in the output with random integers. I have attached the screenshot. But this behaviour is not observed when I copied the same program in my windows PC.

Please help in this regard.

I am attaching the C++ program file as well as the screenshot of the output.

Replies

Off-by-one error: the 3rd argument to mergeSort needs to be the index of the last array element, not the array size. So you are actually sorting 14 elements including the garbage value past the end of the array, rather than 13 elements. The varying output depends on whether that garbage value sorts into the first 13 elements or not.

If it always “works” on Windows then the stack may be pre-filled with a debug byte value that is always greater than 7, rather than random bytes seen on the Mac.

  • Thanks Mr. Scott. I tried your solution and it worked. Learnt a lot from this regarding the way languages and OSs deal with out of bounds data.

Add a Comment

What Scott J said plus…

The weird thing I am facing is that sometimes it replaces some integers in the output with random integers.

This bug results in undefined behaviour, which explains why it works on some platforms and fails mysteriously on others. To uncover this I plonked the code into an Xcode project (creating from the macOS > Command Line Tool target) and ran it on my Apple silicon Mac (Xcode 13.1 on macOS 12.1). I then enabled Address Sanitizer, as described in Diagnosing Memory, Thread, and Crash Issues Early. When I ran the pogram it pinpointed the exact point where things go wrong, namely line 14:

a2[i] = arr[mid+1+i];

In the debugger I see that mid is 12 and i is 0, which means you’re accessing arr[13], which is out of bounds.

If you’re working in an unsafe [1] language (C, Objective-C, C++), these sanitisers are the only way to… hey hey… stay sane.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

[1] I’m specifically referring to memory safety here. In that context languages like Swift and Rust are memory safe, but C and friends are not.

  • Thanks Mr. Quinn. I learnt a new thing called memory safety here. It will be a new concept in my journey of learning to program.

Add a Comment

Also check out session video Understanding Undefined Behavior from WWDC17.

  • Oh, yeah, that's a great talk!

Add a Comment