samedi 7 octobre 2017

Why doesn't deleting a pointer do anything? [duplicate]

This question already has an answer here:

When I run the following code on Xcode:

int *a, *b;
a = new int;
b = new int;

cout << "dyanmically allocate new int var & store pointer in a & b" << endl;
cout << "b value is " << *b << " b pointer is " << b << endl;
cout << "a value is " << *a << " a pointer is " << a << endl;

*a = 5;
*b = *a;

cout << "Put what is stored in the memory pointed at by a into the memory pointed at by b" << endl;
cout << "b value is " << *b << " b pointer is " << b << endl;
cout << "a value is " << *a << " a pointer is " << a << endl;

cout << "delete a" << endl;

delete a;

cout << "b value is " << *b << " b pointer is " << b << endl;
cout << "a value is " << *a << " a pointer is " << a << endl;

I get the following output on the console:

dyanmically allocate new int var & store pointer in a & b
b value is 0 b pointer is 0x100550830
a value is 0 a pointer is 0x100550700
Put what is stored in the memory pointed at by a into the memory pointed at by b
b value is 5 b pointer is 0x100550830
a value is 5 a pointer is 0x100550700
delete a
b value is 5 b pointer is 0x100550830
a value is 5 a pointer is 0x100550700

And what I don't understand is when I delete a why does *a and a still work? If I deleted a pointer shouldn't it throw an error or reference an invalid address?

Aucun commentaire:

Enregistrer un commentaire