0

This is part of a homework assignment, and the wording of the question is kind of confusing me. Say I want to traverse a list. I'll set a temporary pointer to the head of the list, and then I'll have it iterate from node to node until I reach the end.

At what point am I allocating node space referred to by the pointer when declaring it? I'm declaring the pointer and setting it to the head of the list? I don't understand what is being allocated here other than a few bits in memory to store the pointer.

Victor
  • 57
  • 2
  • 8
  • What's the full question? – Chris Culter Oct 14 '14 at 04:54
  • 1
    When you create a temporary pointer to traverse a list, what is the danger in allocating Node space referred to by the pointer when declaring the pointer? We are working with BST's. I'm just assuming that she is asking what would happen if I allocated a new node when making the temp pointer. It's just hard to wrap my head around because the thought of that sounds ridiculous. – Victor Oct 14 '14 at 04:58
  • Huh. Yeah, I'd say to trust your first guess. It does sound ridiculous, but you could imagine a beginner student who assumes that every pointer declaration must be initialized with a new allocation. Maybe the professor has taught such students in the past, so now she uses this question to root out the misconception. – Chris Culter Oct 14 '14 at 05:16

1 Answers1

2

I guess it's that you would have a memory leak if you allocate a Node, store it in your temporary pointer, then step that pointer down the list. You'll never be able to free the Node you created (which anyway was useless).

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • Agreed. A good habit to get into is that unless you are explicitly initializing the pointer when you declare it, or are going to assign into it within a couple of lines, then initialize it to `NULL`. – dgnuff Oct 14 '14 at 06:10