int* p; //pointer (value : 0x deadbeaf, location: 0x aaaaaaaa)
p=newint();
*p=8; // value situated on the place: 0x deadbeaf
...
delete p;
When we delete p, we acutally delete just the name of the pointer.
But, so, there is no more variable p situated on location 0x aaaaaa and having value 0x deadbeaf
But, the same location: 0x deadbeaf has still the value 8, does it?
Would not : delete *p
clean the memory location 0x deadbeaf of its value 8?
Please help, many thanks!!!
(p.s. : I understood, delete p is expression that directly means cleaning the value from the heap memory, just checking if I misunderstod sth).
Yes, p has an address (we can call it 0xDEADBEEF if you like lol)
on line 2 you allocate space for 1 int at that address
on line 3 you assign the int at that address the value 8
on line 6 you free the memory previously allocated as int
You are not just "deleting the name of the pointer" but the memory allocated at the address of the pointer. The value 8 may indeed still exist at the memory block but it is not guaranteed to be.
#include<iostream>
usingnamespace std;
int main()
{
int *p;
cout << "Pointer p at address " << &p << " unallocated space value is " << *p << endl;
int p2 = 5;
cout << "Int p2 at address " << &p2 << " stack space value is " << p2 << endl;
p = newint(10);
cout << "Pointer to p at address " << &p << " heap space value is " << *p << endl;
int *q = p;
cout << "Pointer q at address " << &q << " heap space value is " << *q << endl;
delete p;
cout << "Pointer p at address " << &p << " freed heap space value is " << *p << endl;
q = &p2;
cout << "Pointer q at address" << &q << " stack space value is " << *q << endl;
return 0;
}
Output:
Pointer p at address 0x28fefc unallocated space value is -1869573949
Int p2 at address 0x28fef8 stack space value is 5
Pointer to p at address 0x28fefc heap space value is 10
Pointer q at address 0x28fef4 heap space value is 10
Pointer p at address 0x28fefc freed heap space value is 10
Pointer q at address0x28fef4 stack space value is 5
After the delete call, the space still contains the value 10, but it is not guaranteed to. It exsists in much the same state as the first call to pointer p before it was allocated.