且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

内存分配(指针和堆栈)

更新时间:2023-01-15 21:44:15

我认为你误解了指针在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