21G. Summary

Expression new T allocates memory in the heap large enough to hold a value of type T. The value of expression new T is the memory address of the newly allocated memory.

Statement

  delete p;
recycles the memory occupied by variable *p by giving it back to the HM. If you say delete p, then p must be an address that you got as the value of an expression of the form new T for some type T. If you break that rule, you poison the HM.

A dangling pointer is a pointer to memory that your program does not own or should not use. Just having a dangling pointer is not a big problem. But beware of using a dangling pointer. It can derail your software in awful ways. The source of the error can be very difficult to isolate during debugging.

A memory fault occurs when your program tries to use memory that the OS knows the program does not own. If your program gets a memory fault, try running a debugger. It will stop the program at the fault and show you just where the program is. Print the values of some relevant variables. If you are not unlucky, you will see some peculiarities that suggest how to fix the problem.