内存分配(指针和堆栈) [英] Memory Allocation (Pointers and Stacks)
问题描述
我创建了一个指针堆栈,用于创建一个二叉树。虽然我可以用单个节点填充堆栈,尝试分配顶部节点的内存到一个新的节点,所以我可以创建一个实际的树,它segfaults。例如:
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.
推荐答案
我认为你误解了指针在C ++ / C中是如何工作的。它们只是表示内存地址的整数值。 new
关键字为一个类分配内存,然后调用该类的构造函数。
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.
所以从你写的内容
TreeNode *c = new TreeNode;
为Treenode分配一个指针。然后为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
获取函数调用stack.top()返回的地址/指针值,并将其赋给变量c。
Get the address/pointer value returned by the function call stack.top() and assign it to the variable c.
正如chris所说,即使你的代码工作,它是一个泄漏,因为在c ++没有垃圾收集器,所以当你做c = stack.top以前分配的只是在堆上丢失。
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.
Treenode *c = new Treenode;
delete c;
c = stack.top();
或
Treenode *c = stack.top();
您可观察到的问题是在调用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
这篇关于内存分配(指针和堆栈)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!