Delete function in C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <string>
using namespace std;

int main(void)
{

    int *p1;
    p1 = new int;
    
    int *p2 = new int;
    
    int *p3;
    
    p3 = p1;
    
    *p1 = 5;
    *p2 = 10;
    
    cout << "p1 = " << *p1 << endl;
    cout << "p2 = " << *p2 << endl;
    cout << "p3 = " << *p3 << endl << endl;
    
    delete p1;
    
    cout << "p1 = " << *p1 << endl;
    cout << "p2 = " << *p2 << endl;
    cout << "p3 = " << *p3 << endl;
    
    getchar();
    return 0;
}


Why is the delete function not working in this case? When I cout *p1 and *p3 it still gives me 5?
Last edited on
On line 27 you are dereferencing a null pointer so I would expect some kind of crash, not any data.

As for p3, which happens to point to where p1 used to point...that memory has been deallocated, so you shouldn't be accessing it. It just so happens there is a 5 there. It could be anything. Your program could even crash if it felt like it.
So it is just a coincidence that it output a 5 for both p1 and p3?

Edit* sorry the p1 = NULL wasnt suppose to be there.
Last edited on
What's going on?

I built the program with:

g++ -std=c++11 -Wall -Wextra -pedantic -pedantic-errors test.cpp

and after running I've got at the output the following state:

1
2
3
4
5
6
7
8
9
./a.out

p1 = 5
p2 = 10
p3 = 5

p1 = 0
p2 = 10
p3 = 0


which it seems to be ok IMO.
Last edited on
Just because you delete data doesn't mean that the data that is being pointed to is reset, though in some cases it might be. It is potential that valid data is still accessible, though its just as likely that the system has now utilized that address in the memory to do something else.

Basically, don't do that. And yes, it was (sort of) just a coincidence.
Delete does not necessarily clear memory, it de-allocates it. This means the contents of the memory may not actually be altered.... but rather... it is no longer allocated so it is free to be allocated elsewhere.

I heard it described as a hotel room once. When you allocate memory with new, it's like you are renting a hotel room. You can put your stuff in that room and it's guaranteed that your stuff will stay in that room for as long as you have it rented.

Once you check out of the hotel (delete the memory), it's possible your stuff will remain in the room for a while. If you sneak back into the room, your stuff might still be there... or it might be replaced with someone else's stuff.
Topic archived. No new replies allowed.