I have a C++ program:
#include <iostream>
char * foo (char * bar, const char * baz) {
int i = -1;
do {
i++;
*(bar + i) = *(baz + i);
} while (*(baz + i));
return bar;
}
int main (int argc, char *argv[]) {
char bar[] = "";
char baz[] = "Hello";
foo(bar, baz);
std::cout << "bar: " << bar << std::endl;
std::cout << "baz: " << baz << std::endl;
}
Not that this is the important part, but the requirement for this program is that it copies one C style string into another using pointers.
When I compile and execute my binary on my Ubuntu 16.04 desktop, this is what I see:
$ g++ -std=c++11 test.cpp -o test && ./test
bar: Hello
baz: ello
Egad! The initial 'H'
of baz
has been dropped, but I don't see how my foo
function changes baz
at all. Hmm...
The g++ version on my Ubuntu desktop is thus:
$ g++ --version
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.12) 5.4.0 20160609
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
I thought this was an error or bug with my code (and it may still be), yet I discovered that when I compile and run on any other operating system I get different behavior.
Here is the output on macOS:
$ g++ -std=c++11 test.cpp -o test && ./test
bar: Hello
baz: Hello
Here is the g++ version on that macOS laptop:
$ g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 12.0.0 (clang-1200.0.32.2)
Target: x86_64-apple-darwin19.5.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
When tested on other Linux boxes, on Windows, etc. it has the correct, expected out put of bar
and baz
both being Hello
.
What is going on!?
tl;dr C++ program outputs a C style string differently on my desktop than any other computer. Why?
Aucun commentaire:
Enregistrer un commentaire