unpointing to "new" allocated memory

Hi, quick question.
What happens to memory that is allocated in a fashion such as this-
Item* temp = new Item ///Item is a struct

when its pointer is reassigned in a manner like this?
1
2
3
4
Item* temp = new Item ///Item is a struct

Item* temp2 = new Item;
temp = temp2;


When it is reassigned to another "new" allocated memory, does it become an unpointed to memory leak? Or does it free itself since its not being pointed to?
I've learned this answer in my studies, but I've forgotten and I can't seem to google the correct phrase question.
Thanks.
Yes, it becomes a memory leak. You have to delete it before you change your pointer, or else you will lose it and won't be able to delete it.
I ask because I need a way to delete a pointer in a linked list.


Would something like this work for a linked list with 3 items?
1
2
3
4
5
6
void remove()
{
Item* temp;
temp = Head->Next;
Head->Next = temp->Next;
}


Head is the latest item in the linked list. Would using an automatic pointer variable like this work?
Pointing it to the address I wish close and then having it automatically delete when the function ends?

If I did it like this:
1
2
3
4
5
6
7
void remove()
{
Item* temp = new Item;
temp = Head->Next;
Head->Next = temp->Next;
delete temp;
}

This would create a memory leak for the "new" allocation, correct?

Heck, could I simply do this?
1
2
3
4
5
6
7
void remove()
{
Item* temp;
temp = Head->Next;
Head->Next = temp->Next;
delete temp;
}

Temp wasn't initialized to new memory, but since it now occupies memory allocated by new, would this work?

Thanks.
flclempire wrote:
Heck, could I simply do this?
;) Yes. calling new in remove() does not make too much sense, hm? But check if temp actually points to an object (don't forget to initialize an empty pointer to null)
Topic archived. No new replies allowed.