1

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;
}
2
  • 4
    Always use exactly one delete for each new Commented Jul 13, 2020 at 23:32
  • p is equal to a, which contains the result of new int(7). Doing delete p followed by delete a therefore releases the same dynamically allocated int twice . That causes undefined behaviour. Commented Jul 14, 2020 at 0:06

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.