0

i have some sample code that behaves different in gcc(6.3) and in MSVC (11). I know that passing raw "hello" is not going to last when i call std::cout. In Microsoft Visual Studio 11 i get the expected output but in gcc the string remains in memory. The problem is that the code in gcc may compile, may behave as expected but is wrong, and i do not know why did not erase the "hello" string from memory. What i am missing? (Ignore the memory leaks is just dummy code)

Edit

The question is more oriented about the difference of compiling with gcc or MSVC. I have already pointed that the code will yield into undefined behaviour. The point is that something like this has been running ok under linux during years and has crashed at first run under a Windows port. Maybe that was only luck but i was asking more about gcc compiler doing nasty things in the background.

MSVC output

w_holder:

Gcc output

w_holder:hello

Code

#include <iostream>
#include <vector>
#include <string>

class StringWrapper
{
public:
    StringWrapper(const std::string& sInput) : _string(sInput) { }

    const std::string& _string;
};

class WrapperHolder
{
public:
    WrapperHolder(const std::string& sInput) { _swrapper = new StringWrapper(sInput); }

    StringWrapper* _swrapper;
};


int main()
{
    WrapperHolder* w_holder = 0;
    w_holder = new WrapperHolder("hello");

    std::cout << "w_holder: " << w_holder->_swrapper->_string << std::endl;

    return 0;
}
SpKel
  • 542
  • 5
  • 15
  • Accessing a destroyed object is undefined behavior. There is no guarantee that the memory that it occupied will be cleared or overwritten. Rather, it's not guaranteed to still be present and intact. Since it's undefined behavior, it could print anything really. It could crash, print garbage, or do anything you can imagine. – François Andrieux Oct 04 '17 at 14:53
  • Memory is not "cleared" when a destructor is called. It's just marked as being free. Some debuggers/compilers might fill memory with a special sequence (like 0xDEADBEEF or 0xCDCDCDCD) to make it obvious when seen in the debugger that something isn't quite right. – Steve Oct 04 '17 at 14:55
  • `-fsanitize=address` – Marc Glisse Oct 04 '17 at 21:53

0 Answers0