Reputation: 17
What is the issue with this code? It gives the output as expected, but there is a runtime error, and I don't know what it is.
Can somebody explain the concept behind it?
int main()
{
int *a = new int(7);//assume the heap memory has address 4F
int *p;
p = a;
cout << a << endl;
cout << p << endl;
cout << *a << endl;
cout << *p << endl;
*p = 10;
cout << *a << endl;
delete p;
delete a;
return 0;
}
Upvotes: 1
Views: 229
Reputation: 36
You reassigned *p = 10
but a
and p
are still the same address in memory. As already mentioned, you are trying to delete the same memory space twice, which can explain the runtime error.
Upvotes: 2
Reputation: 12909
The error is due to the fact that a
and p
point to the same object, and so by doing
delete p;
delete a;
You are deleting 2 times the same object, and so the second time you are trying to delete memory that is already been freed
Upvotes: 1