1

I tried below C++ code

#include <iostream>
using namespace std;

int main()
{
    int *p = new int;
    *p = 10;
    int &a = *p;
    delete p;
    a = 20;
    cout<<a<<" ";
    cout<<*p;
    return 0;
}

and got output as: 20 20

I thought this may cause runtime error as result of accessing freed memory or some garbage. Probably I got this output as memory location freed by program may haven't been used so far so still retaining old values.

So I thought that it should also happen if I don't use references

#include <iostream>
using namespace std;

int main()
{
    int *p = new int;
    *p = 10;
//  int &a = *p;
    delete p;
//  a = 20;
//  cout<<a;
    cout<<*p;
    return 0;
}

but in this case I got output as 0 (checked with multiple runs). Does Reference has anything to do with different outputs?

Compiler: gcc version 4.7.2 (Ubuntu/Linaro 4.7.2-2ubuntu1)

user2078670
  • 43
  • 1
  • 5

2 Answers2

2

You are dereferencing released memory. This is undefined behaviour. There is no guarantee what the result will be. It just happens that with your combination of compiler, operating system, and C++ library, the program appears to work.

This is one possible outcome of undefined behaviour.

Sylvain Defresne
  • 42,429
  • 12
  • 75
  • 85
1

Dereferencing delete-d memory is undefined behaviour and there's no point figuring out some patterns as switching to another compiler or another release of the same compile could break it.

delete calls destructors of non-primitive types. If you have a class Integer wrapper that clears the content when destroyed, you'll see some difference. On primitive types, delete does not re-initialize the space released. Therefore you might see the original value retained but this is not guaranteed to work at all and you should never rely on it.

phoeagon
  • 2,080
  • 17
  • 20