So to understand new/delete better (really to prove to myself with small examples why virtual destructors are needed for interfaces), I want to understand memory leaks, so that
// Reserve some memory for an int and set that memory to the value 43.
int* P1 = new int(43);
// Print the address of the reserved memory.
cout<<"P1 = "<
If you would uncomment the P2 line, it is quite likely that it would be assigned the same memory which would change the value printed at the last line.
Accessing memory that has been freed with delete
causes undefined behaviour as others have pointed out. Undefined includes crashing in strange ways on some cases (only during full moon perhaps? ;-). It also includes everything working perfectly well for now, but with the bug being a mine that can trip off whenever you make another change anywhere else in your program.
A memory leek is when you allocate memory with new
and never free it with delete
. This will usually not be noticed until someone runs your program for a longer period and finds out that it eats all the memory of the system.