Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
145 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...