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
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:
The reference
rPtrnow refers to the integer you created with the linenew int(113). On the next line, you executeThis 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 printrPtrwithAnything 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!