简体   繁体   中英

Pointers in c++ and runtime errors

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;
}

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM