Does anyone know why GCC is incorrectly changing my c_str pointer?

Viewed 168

The code is attached as a picture for slightly easier viewing, but essentially this:

#include <iostream>

using namespace std;

int main() {
    string manu = "Lamborghini";
    const char *const c_manu = manu.c_str();

    string new_manu(c_manu);
    manu[0] = 'P';

    cout << c_manu << endl;
    cout << new_manu << endl;

}

Spits out:

Pamborghini
Lamborghini

This is what I was expecting.

However, if you create a new string from the string that the c_str points at like this:

#include <iostream>

using namespace std;

int main() {
    string manu = "Lamborghini";
    const char *const c_manu = manu.c_str();

    string new_manu(manu);
    manu[0] = 'P';

    cout << c_manu << endl;
    cout << new_manu << endl;

}

Then it spits out:

Lamborghini
Lamborghini

I'm using GCC with CLion, someone ran the exact same code in VSCode and got the expected results for both cases.

Windows 10 x64

CLion 2020.3.3

cygwin64 3.2.0

CMake 3.17.5

Make: make.exe

C Compiler: gcc.exe

C++ Compiler: c++.exe

(all three bundled with cygwin)

Weird new string bug in clion

0 Answers
Related