Reusing a pointer

Nov 21, 2012 at 8:29pm
Let's say we have this situation:

1
2
3
4
5
int* arr = new int[n];
//Do some stuff that alters arr
//Now I want a fresh array to work with
delete [] arr;
arr = new int[n];


Is this going to cause some unforeseen/unpredictable behavior?
Nov 21, 2012 at 8:34pm
It should be fine.
Nov 21, 2012 at 8:47pm
I wasn't sure. I've read similar things that say don't ever do anything with a pointer after deletion. So far from testing it all seems good, but I don't want it to blow up on me down the road.
Nov 21, 2012 at 9:01pm
ResidentBiscuit wrote:
I've read similar things that say don't ever do anything with a pointer after deletion. So far from testing it all seems good, but I don't want it to blow up on me down the road.


You probably misread what those things said - they meant that the object(s) that the pointer was pointing at should not be used/read/messed/written to after thedelete function was called on the pointer - because when you call delete you are basically telling the system to call the destructutors for the objects and reclaim the memory that it so kindly lent us when we called new.

Last edited on Nov 21, 2012 at 9:01pm
Nov 21, 2012 at 9:04pm
Ah that makes sense. So the pointer itself is just fine to keep using. Good good
Nov 21, 2012 at 9:08pm
You could treat a pointer on which a "delete" has been applied to practically the same as using an uninitialized pointer. Meaning - it will start throwing problems if you try to use its location without initializing it first (with new, other memory allocation methods or by assigning it to something else). Other than that, no trouble.
Topic archived. No new replies allowed.