I’m pretty sure this is a basic question, but I can’t find the answer anywhere(maybe because of the wrong search terms).
Is the following code creating a memory leak?
int * ptr= new int(15);
ptr= new int(25);
Do I have to delete the first pointer before calling the new operator on the same pointer for a second time?
Just to clear things up a little actually.
Newwill give you a “random” pointer from the heap and the only guarantee is that you can fit your requested amount of bytes into the block of memory your pointer points to.Consider the following:
int *x = new int;Pointerxnow points to say 0x12345678, and there’s a place for an integer there and the only way you can get to this integer is to use the address that’s stored in your pointerx.Now suppose you call new again.
x = new int;The integer room at 0x12345678 stays “reserved” for you yet your pointer now points elsewhere, say to 0x87654321 where there’s been a new “spot” made for the new integer, and the pointer to the previous one is lost forever, since your pointer no longer points to the original part of the heap.Solution to this problem would be calling
deleteon the pointer, which would NOT touch the pointerxitself, it would simply deallocate the memory from the heap that the pointer just happens to point to. (And as a direct result of that, thexitself would change but just becausenewwould assign the value to it …)Now you can freely call
newyet again.(edit) Yes,
newdoes call the constructor for you but that’s not the point here really.