livefun
livefun

Reputation: 21

About delete in C++

I'm freshman in c++. What's the difference between "delete a" and "delete b" ? Thanks a lot!

    int* a = NULL ;
    int* b = new int(10) ;
    a = b;
    
    delete a;//does the space of b free?
    delete b;

ps:my bad!i dont mean delete a,b at same time,it's actually two ways of delete memery which i wanna ask.

Another question!

How to release the int allocated by the expression new int(10) in case 2?

//case 1: right 
    int *a= new int(10);
    delete a;
//case 2: 
    int b = *new int(10); // how to release the int?

Upvotes: 1

Views: 123

Answers (1)

Jeffrey
Jeffrey

Reputation: 11400

You called a single new, you need to a call a single delete. After a = b; you can delete either one. But you must delete only one. Deleting through either pointer will have the same effect. After the delete call, both variables will become invalid, pointing to freed memory.

Upvotes: 2

Related Questions