+ 2

C++ deleting twice

... int main () { int *p = new int; *p = 5; cout << *p << endl; delete p; *p = 25; cout << *p << endl; delete p; cout << "check"; return 0; } check does not appear. No code after the second delete appears. from my understanding, delete removes the data at p, "*p", but not the pointer itself "p", so I can reuse it whenever needed. I read that deleting twice can cause problems. in my testing, cout << "*p"; yielded 5903056 after deletion, so I can see why it can cause problems, but i overwrote that 5903056 to 25, so the second delete should just remove the 25 and give me some random number again. Why is this happening?

20th Mar 2019, 5:04 PM
HectorMC
HectorMC - avatar
3 Réponses
+ 8
`delete` does not delete the data. It only marks that area in memory as "free to use", and the memory manager will be able to reuse that memory some time later when you do `new` somewhere else in your code. You don't really have control over any of that though. Practically speaking `delete` revokes your access to that memory and after deleting you may not write to that location anymore. The pointer still points there though, so some programmers will even do `p = nullptr;` to make sure that it won't be used accidentally. If you're lucky, writing to free'd memory will work without error, but it won't in general, and it will probably cause a mess later on during program execution.
20th Mar 2019, 5:34 PM
Schindlabua
Schindlabua - avatar
+ 5
Yep, `p` is unusable. `new` borrows memory and `delete` gives it back basically. I don't write much C++ and I don't know the style guides but it can't be a bad habit to pick up. Personally I don't bother nulling pointers though. I think if you're writing modern C++ you will try to avoid raw pointers and use smart pointers instead most of the time, so you don't have to worry about `delete` at all.
20th Mar 2019, 6:45 PM
Schindlabua
Schindlabua - avatar
+ 1
Is pointer p unusable after you delete it? I can't create a new int since it's declared and trying to write in it can cause problems (from what i understood from you, I don't have enough machines to test it). So would it be a good habit to nullptr after every deletion?
20th Mar 2019, 6:30 PM
HectorMC
HectorMC - avatar