C++ Multiple new on single pointer

c++, memory-leaks

Solution

Just to clear things up a little actually. `New` will 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;` Pointer `x` now 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 pointer `x`.

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 `delete` on the pointer, which would NOT touch the pointer `x` itself, it would simply deallocate the memory from the heap that the pointer just happens to point to. (And as a direct result of that, the `x` itself would change but just because `new` would assign the value to it ...)

Now you can freely call `new` yet again.

(edit) Yes, `new` does call the constructor for you but that's not the point here really.

Problem

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?

Original source