3

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 :)

Leed
  • 33
  • 3

1 Answers1

3

(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.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • It could also depend on how the `<<` operator uses memory. If `std::string` uses SSO, it will also depend on whether the temporary string is small enough to fit; if so, `p` will point to an on stack location, which will be overwritten when `operator<<` is called. And so on: you really can't make any general statement. – James Kanze Apr 25 '14 at 08:31
  • Thanks @Luchian Grigore I think Visual Studio bother with optimizations :) – Leed Apr 25 '14 at 08:34