When should I delete my in-function pointers?

I'm sorry if this is in the wrong section, I'm brand new here.
I have a function that is supposed to take in movie information from a file, and organize it into a linked list. The function is kind of big, but I'll try to cut out all of the non-relevant content.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
movie* TakeInput()
{
	ifstream inFile;
	movie* mPtr;
	movie* head;
	head = NULL;

	inFile.open("file.txt");

	//PROCESSING - builds the list
	while (!inFile.eof())

	{
		mPtr = new movie;

		inFile >> mPtr -> score;

		mPtr -> next = head;
		head = mPtr;
	}
	inFile.close();

	delete mPtr;
	return head;
}

The problem seems to be coming from "delete mPtr;" When I get rid of that line, it seems to works perfectly. I'm completely lost as to why this is. From my end of the compiler it looks like head isn't returning properly without it.
EDIT: Sorry, I should probably tell you that the symptom of deleting mPtr is that the last item to be read in my list gets all sorts of problems that I can't keep track of when I try out-puting the contents. The other items in the list seem to be fine though.

So my question is, why can't I delete mPtr. It doesn't deallocate it self at the end of the function, right? Also, If I'm returning the head of my linked list, how do I even deallocate that. Should I be passing by reference?
Last edited on
mPtr and head both pointy to the same memory address, so deleting mPtr has the same result as deleting head. You have to delete your pointers when you're not going to use what they point to any more. In this case, the pointed object is a part of the list which you intend to use in the future.
Oh. I see now. For some reason, I was thinking that I was deleting the variables themselves, but instead it's deleting the information the pointer created. Upon closer examination, I am a moron. So just for future reference, I only need to use delete when I'm dealing with new, right?
right
Topic archived. No new replies allowed.