问题描述:

I've created a stack of pointers, which is being used to create a binary tree. While I can fill the stack with individual nodes, upon trying to allocate the top node's memory to a new node so I can create an actual tree, it segfaults. As an example:

TreeNode *c = new TreeNode;

c = stack.top(); //this segfaults

I'm not sure if I'm misunderstanding how this works, but since both are of the same type, shouldn't c be able to equal the top of the stack? I've been stuck on this for hours now.

网友答案:

I think you are misunderstanding how pointers work in C++/C. They are just integer values that represent memory addresses. The new keyword assigns memory for a class and then calls the constructor for that class.

So from what you have written

TreeNode *c = new TreeNode;

Allocate a pointer for a Treenode. Then allocate the memory for a Treenode, call it's constructor and assign the address of this memory block to the pointer.

c = stack.top(); //this segfaults

Get the address/pointer value returned by the function call stack.top() and assign it to the variable c.

As chris said, even if your code had worked it is a leak as there is no garbage collector in c++ so when you do c= stack.top() the memory previously assigned is just lost on the heap.

Either

Treenode *c = new Treenode;
delete c;
c = stack.top();

Or

Treenode *c = stack.top();

Your observable problem is in the call to stack.top() somewhere. I'd suggest a pointer tutorial like this.

http://www.codeproject.com/Articles/627/A-Beginner-s-Guide-to-Pointers

相关阅读:
Top