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

4

1 回答 1

3

(hello+world).c_str()仅在尾随;. 之后访问内存是未定义的行为。

Visual Studio 可能实际上会清除内存,Dev-C++ 不会打扰。尝试使用 Visual Studio(优化)构建发布版本,您可能会看到相同的行为。

于 2014-04-25T08:26:07.717 回答