C ++ Multiple New On One Pointer

I am sure this is the main question, but I can not find the answer anywhere (possibly due to incorrect search conditions).

Is the following code creating a memory leak?

int * ptr= new int(15);
ptr= new int(25);

Should I delete the first pointer before calling the operator newon the same pointer a second time?

+3
source share
4 answers

Just to figure it out a bit. Newwill give you a "random" pointer from the heap, and the only guarantee is that you can put the requested number of bytes in the memory block that your pointer points to.

Consider the following:

int *x = new int; x 0x12345678, , , , - , x.

, . x = new int; 0x12345678 "" , , , 0x87654321, "" integer, , .

delete , x, , . ( , x , , New ...)

New .

() , New , .

+5

, ptr new. , 1- .

ptr, delete .

+5

?

, .

Should I delete the first pointer before calling a new operator on the same pointer a second time?

Yes, you must deleteselect everything newbefore losing all links to it and you will no longer be able to free it.

+5
source

Yes and yes. Every time you use new, you must use delete, a copy of it.

+4
source

All Articles