I'm trying to understand more in details the concept of
premature deletion
The following is taken from "The C++ Programming Language" book, 11.2.1
1 2 3 4 5 6 7 8 9 10 11
|
#include <iostream>
int main() {
int *p1 = new int{99};
int *p2 = p1;
delete p1; //now p2 doesn't point to a valid object
p1 = nullptr; //gives a false sense of safety
char *p3 = new char{'x'}; //may point to the memory pointed to by p2
*p2 = 999; //may cause trouble
std::cout << *p3 << "\n"; //this may not print x
return 0;
}
| |
As written in the comments, that line
may not print
x
. I need to figure out if I understand correctly each step.
- After the statement
delete p1;
I will allow the OS to write over the memory location pointed to by
p1
- Here be dragons, because the statement
char* p3 = new char{'x'};
may write over that memory location, which is still pointed by
p2
.
- If now I dereference
p2
and write
*p2 = 999;
I may be writing over the memory location where
'x'
was written.
Is my summary above correct? If so, I can't understand why if I compile and run this code I cannot see neither
'x'
nor
999
, but just a
�
. What's the source of this?
Maybe because I'm writing an integer where now it's expected to be written a char, and hence a conversion is performed at run-time, giving that strange result?