0

Let's consider the following example of having reference to already destroyed object.

struct Config
{
    unsigned int m_maxSize = 1;
};

class FileReader
{
public:
    FileReader(Config& config) : m_cfg(config){
    }

    Config& m_cfg;
};

class FileReaderUser
{
    FileReader* m_fileReader;
public:
    FileReaderUser(){
        Config cfg;
        cfg.m_maxSize = 1234;
        m_fileReader = new FileReader(cfg);
    }

    void PrintSize(){
        std::cout << "Config value: " << m_fileReader->m_cfg.m_maxSize << std::endl;
    }
};

int main()
{
    FileReaderUser fileReaderUser;
    fileReaderUser.PrintSize();
}

In this example output is 0. My question is why is it zero? I would expect to have access violation if memory was already taken by some other object (not sure if it's true), or to have untouched old (1234) value. It's compiled on GCC 7.2.0 in Debug.

Adam Stepniak
  • 815
  • 6
  • 21

1 Answers1

4

My question is why is it zero?

Because the behaviour of the program is undefined. This is one possible behaviour that the program could have.

I would expect to

It is foolish to expect any particular behaviour. None of your expectations are guaranteed to be correct.

expect to have access violation if memory was already taken by some other object

Memory access violations are detected by the operating system. The operating system has no knowledge of "objects" that the C++ program uses, so whether some piece of memory is used by one object or another is not known to the OS. You get access violations when you attempt to access memory pages that have an invalid mapping.

More generally, the language does not guarantee that you will get a memory access violation if you access objects outside of their lifetime. In fact, I don't think there are any situations where the C++ language would have such guarantee.

or to have untouched old (1234) value

There is no guarantee that you get the untouched value when you access an object outside of its lifetime. There are no guarantees whatsoever.

eerorika
  • 232,697
  • 12
  • 197
  • 326