How can I use the deleted pointer again?

I want to use a deleted pointer again so I did like this

int* a1=new int;
int* a2=new int;
.
.
.
delete a1;
*a1=*a2;
delete a2;

but I got segment fault..
what is wrong part??
Can I eat a hamburger twice?

Yes, surely I can, but the second time I will be eating poo.



You can always reuse variables. But once you tell the memory manager that you are done with dynamically-allocated data, you have no right to it. Why is it a surprise that it barfed when you tried to use something you deleted?
delete means "the memory that this pointer is pointing to; I don't want it anymore. Please call the destructor of the object at that memory location, and after that you can do whatever you like with it".
Last edited on
int * a = new int;
a[0] = 3;
delete a;
//if you try to reference a between the above and below it will seg fault.
//some people put a=0 or a=nullptr here. it isnt necessary, but it can give better debugging results if you make a mistake.
a = new int;
a[0] = 5; //now you can use it again. its not generally the same memory location as it was above.
...

this is inefficient. asking for and releasing memory is an expensive OS call. better to avoid this if at all possible, and just say
a[0] = 3;
... whatever else
a[0] = 5;

without destroying and recreating it.
Last edited on
Lovely analogy, Duthomhas :D Although might take some time to digest...
I had my suspicions in the earlier thread http://www.cplusplus.com/forum/general/242712/

... but I never anticipated the benefit of doubt to end up in a hamburger.
Topic archived. No new replies allowed.