What does delete command really do for memory, for pointers in C++?
c++, memory-management, new-operator
Solution
Think of memory as a big warehouse with lots of boxes to put things into. When you call "new", the warehouse staff finds an unused box large enough for your needs, records that box as being owned by you (so it's not given to someone else), and gives you the number of that box so you can put your stuff into it. This number would be the "pointer".
Now, when you "delete" that pointer, the reverse happens: the warehouse staff notes that this particular box is available again. Contrary to real warehouse staff they aren't doing anything with the box — so if you look into it after a "delete" you might see your old stuff. Or you might see somebody else’s stuff, if the box was reassigned in the meantime.
Technically, you are not allowed to look into your box once you have returned it to the pool, but this is a somewhat weird warehouse with no keys or guards, so you can still do whatever you want. However, it might cause problems with the new owner of the box, so it's expected that you follow the rules.
Problem
Possible Duplicate: C++ delete - It deletes my objects but I can still access the data? Can a local variable's memory be accessed outside its scope? I do not understand what `delete` really does when I want to free memory allocated with `new`. In C++ Premiere book it is written: This removes the memory to which ps pointer points; it doesn’t remove the pointer ps itself. You can reuse ps, for example, to point to another new allocation. You should always balance a use of new with a use of delete; otherwise, you can wind up with a memory leak—that is, memory that has been allocated but can no longer be used. If a memory leak grows too large, it can bring a program seeking more memory to a halt. So as I understand `delete` must delete the value in the memory to which pinter points. But it doesn't. Here's my experiment: ``` int * ipt = new int; // create new pointer-to-int cout << ipt << endl; // 0x200102a0, so pointer ipt points to address 0x200102a0 cout << *ipt << endl; // 0, so the value at that address for now is 0. Ok, nothing was assigned *ipt = 1000; // assign a value to that memory address cout << *pt << endl; // read the new value, it is 1000, ok cout << *((int *) 0x200102a0) << endl; // read exactly from the address, 1000 too delete ipt; // now I do delete and then check cout << ipt << endl; // 0x200102a0, so still points to 0x200102a0 cout << *ipt << endl; // 1000, the value there is the same cout << *((int *) 0x200102a0) << endl; // 1000, also 1000 is the value ``` So what does `delete` really do?