3
#include <iostream>
#include <fstream>
int main(int argc, char* argv[])
{
    const std::string string_2 = "string_2";
    const std::string string_1 = "string_1";

    std::cout << string_2 << std::endl;
    std::cout << string_1 << std::endl;
    std::fstream beep("abcd");
    std::cout << string_2 << std::endl;
    std::cout << string_1 << std::endl;
    printf("%s", string_1.c_str());
}

I am using CMake. When I run this with set(CMAKE_CXX_FLAGS_RELEASE "-O0 -DNDEBUG"), I get the following bad output:

string_2
string_1
string_2
╘       ±o☻
╘       ±o☻

But when I run it after compiling it with -03, the problem does not exist.

Clearly, string_1's value has been changed by the instantiation of an ifstream.

If I change the code to define string_2 after string_1, it is instead string_2 that is changed. If I make the strings static, then no change occurs.

So what is clear to me is that the most recently-defined string which is not static is having its value corrupted when the fstream is instantiated.

Why could this be happening?

I am using CLion 2019.1, using a MinGW environment (mingw-w64\i686-8.1.0-posix-dwarf-rt_v6-rev0\mingw32)

Using the bundled CMake, and MinGW's bundled g++.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Daniel Paczuski Bak
  • 3,720
  • 8
  • 32
  • 78
  • Where is `#include `? Don't make the mistake of assuming things work without having that header included. Also CLion is not a C++ compiler -- it is an IDE. Probably you're using `gcc`. – PaulMcKenzie Oct 08 '19 at 01:09
  • The same problem exists whether or not I #include . I've updated the post with some environment info. – Daniel Paczuski Bak Oct 08 '19 at 01:13
  • General rule of thumb is if a problem exists in debug mode but not in optimized, there's UB and debug caught it. Optimized code makes the assumption there isn't UB so things can appear to work. For a while. – doug Oct 08 '19 at 01:20
  • Can you clarify, what's UB? – Daniel Paczuski Bak Oct 08 '19 at 01:25
  • 2
    This seems like you have an ABI mismatch between the headers you’re including and the standard library implementation you’re linking to. – Davis Herring Oct 08 '19 at 07:21
  • UB = [undefined behavior](https://stackoverflow.com/q/2397984/). – L. F. Oct 08 '19 at 13:49

0 Answers0