Premature deletion: CPL book example

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?
Last edited on
1) yes.
2) yes
3) yes. *pw = 999 will clobber whatever has been allocated to that memory location since delete p1

*p3 is a type char. So displays as a char the contents of the memory location pointed to by p3. *p2 is of type int (usually 4 bytes) 999 is an int which is saved at the 4 bytes pointed to by p2. So *p3 just displays the contents of the first byte of these which happen to the binary code for the ASCII char � which is then displayed.

The above code is an example of what can happen when using pointers wrong - and is one of the reasons you should be using managed pointers instead (unique_ptr, shared_ptr) etc.
Thanks @seeplus for your check. I know it's better to use manager objects like unique_ptr when I have to construct objects on the heap, and indeed I've been using them in my projects.

However, sometimes when I look at book I feel the need to check and understand "buggy" examples like the one above :-)
Topic archived. No new replies allowed.