Does 'delete' free memory

Hi, guys, I have a question here. As described in the title, when we delete a dynamically initialized pointer, does 'delete' free the memory that's been allocated to store the object that the pointer points to? As what I learnt, it should free the corresponding memory, but when I tried to access a deleted pointer with code shown below, it worked just fine and there was no sign of the pointer being deleted.

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
using namespace std;
int main()
{
    int *p = new int(0);
    cout << p << " " << *p << endl;
    delete p;
    cout << p << " " << *p << endl;
    *p = 4;
    cout << p << " " << *p << endl;
}

As you can see, after I deleted 'p', I assigned a new value to the object that
'p' pointing to, and it could be printed out without generating any error. If
the memory of the object that 'p' pointing to was indeed deleted, then there
should be no way that I could continue to use the pointer, is it?
does 'delete' free the memory that's been allocated to store the object that the pointer points to?


Yes.

when I tried to access a deleted pointer with code shown below, it worked just fine and there was no sign of the pointer being deleted.


Trying to access a deleted pointer... or any pointer that does not point to allocated memory results in undefined behavior. It might work just fine... or it might cause your program to crash.. or it might corrupt the heap.

Delete is kind of a misnomer. The memory is still there... you just have told the computer that you don't need it anymore. At which point the computer may or may not assign that memory to other things.
You shouldn't use new and delete. Trying using handlers.


Asus
Okay, get it. Thanks a lot guys!
Topic archived. No new replies allowed.