Memory Allocation (Pointers and Stacks)

混江龙づ霸主 提交于 2019-12-26 06:49:04

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/12575825/memory-allocation-pointers-and-stacks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!