I saw a lot of similar questions about deleting twice, but what happens when you allocating twice and delete only once? isn't the old version is still exist and how does the program compile?
Don't I have to kind of release the new one too, because according to the d'tor it gets called only once.
For example:
int main()
{
int *ptr = new int;
*ptr=5;
ptr=new int; //again, different memory location
*ptr=25;
delete ptr;
return 0;
}
what with the 5?? it will be a memory leak or something?
what with the 5?? it will be a memory leak or something?
Yes! The second new
will overwrite ptr
, and you will need the old address for deleting the first allocation. Unless you save ptr
it in another variable, or delete it before the second new
, or use another variable name for the second pointer, you will have no way of knowing the address of the first memory block, and you will not be able to free it. That is a memory leak.
By the way, welcome to SO