deadmau5
deadmau5

Reputation: 95

Reference of a pointer returning weird value

Can anyone explain to me why this code works (why does it return a value)?

int main()
{
    int *ptr = new int(113);
    int &rPtr = *ptr;

    delete ptr;

    cout << rPtr << endl;

    return 0;
}

Basically, this is the return value that I get:

-572662307

Upvotes: 2

Views: 1697

Answers (3)

templatetypedef
templatetypedef

Reputation: 372684

What you are doing results in undefined behavior, so the fact that you're getting this number is perfectly reasonable behavior.

When you perform this sequence:

int *ptr = new int(113);
int &rPtr = *ptr;

The reference rPtr now refers to the integer you created with the line new int(113). On the next line, you execute

delete ptr;

This deletes that int, meaning that the object no longer exists. Any pointers or references to it now reference a deallocated object, which causes undefined behavior. Consequently, when you print rPtr with

cout << rPtr << endl; 

Anything can happen. Here, you're just getting garbage data, but the program easily could have crashed or reported a debug error message.

Interestingly: The value you printed (-572662307), treated as a 32-bit unsigned value, is 0xDDDDDDDD. I bet this is the memory allocator putting a value into the deallocated memory to help you debug memory errors like this one.

Hope this helps!

Upvotes: 3

ForEveR
ForEveR

Reputation: 55887

Reference for object is alive in all block scope (in this case function scope), so when you delete pointer, some garbage was at this address and output shows it.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258548

You're invoking undefined behavior. The reference is no longer valid after deleting the pointer:

int *ptr = new int(113);
int &rPtr = *ptr;
//rPtr references the memory ptr points to
delete ptr;
//the memory is released
//the reference is no longer valid
cout << rPtr << endl;
//you try to access an invalid reference
//anything can happen at this point

Upvotes: 0

Related Questions