Why is there a difference between using c++ string+string temporary object by different compilers? [duplicate]

StackOverflow https://stackoverflow.com/questions/23287894

  •  09-07-2023
  •  | 
  •  

Please look at this code.

#include <iostream>
#include <string>
using namespace std;

int main() {
    string hello = "Hello"
         , world = "World";

    const char *p = (hello+world).c_str();
    cout << "STRING: " << p <<endl;

    return 0;
}

I have no reputation, can't post images so that I will write results by hand.

= Visual Studio 2013 ver.12.0.30110.00

STRING: 

= Dev-C++ ver.4.9.9.2

STRING: HelloWorld

The first following is execution result that compiled by Visual Studio.

Second is compiled by Dev-C++.

I wonder what makes this difference.

I will be looking forward to your reply. Thanks :)

有帮助吗?

解决方案

(hello+world).c_str() is only valid until the trailing ;. Accessing the memory afterwards is undefined behavior.

Visual studio probably actually clears the memory, Dev-C++ doesn't bother. Try building a release version with Visual studio (optimizations on) and you'll probably see the same behavior.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top