Question: I am implementing a Huffman encoder. Huffman trees are built bottom-up using a priority queue. I have a simple node class with pointers to two other nodes.
The loop that builds the tree is:

```
while(q.size() > 1)
{
    huffnode n1 = q.top();
    q.pop();
    huffnode n2 = q.top();
    q.pop();

    q.push(huffnode((char)0, n1.freq+n2.freq, &n1, &n2));
}

```

The remaining node when the loop terminates is the tree root.

This code looks innocent enough, but on my test input it gives a tree where the root's right child points to itself and to the root's left child instead of to the two nodes that were just popped from the queue. I have confirmed that the queue is sorted correctly. 

What I think is happening is that n1 and n2 are local variables that always have the same address, as seen in the debugger. When a new node is pushed, it points to those addresses. When that node gets popped later, its copy gets put into one of those addresses, one of which it is already pointing to, so it ends up pointing to itself.

How should I fix this? I can't make n1 and n2 pointers, because then they would have to be `const` since top() returns a const reference, and assigning the result of top() to a const reference or const pointer makes the queue immutable.

Answer: 
When you have the curly braces `{}` you are in a new scope. and variables declared in that scope are local to that scope and only valid inside that scope. When the scope ends, which for you your loop is every time the loop iterates, the scope disappears and the variables in that scope are destructed and exists no more.

Saving a pointer to a variable that goes out of scope will lead to *undefined behavior* when you try to dereference that pointer.
comingstorm is right. I need to use `new`.

The fixed code is 

```
while(q.size() > 1)
{
    huffnode* n1 = new huffnode(q.top().data, q.top().freq, q.top().left, q.top().right);
    q.pop();
    huffnode* n2 = new huffnode(q.top().data, q.top().freq, q.top().left, q.top().right);
    q.pop();

    q.push(huffnode((char)0, n1->freq + n2->freq, n1, n2));
}

```