链表实现问题
我正在尝试使用底层链表结构创建一个堆栈。
也许我错了,但我在使用remove()函数时遇到了问题。
int Stack::remove(){
node* victim = new node;
int popped;
popped = top->element;
victim = top;
top = victim->next;
delete victim;
return popped;
}
我正在检测 glibc
双重释放或腐败(出局);
由于我正在为受害者分配新的内存,所以我是否必须删除受害者,或者这是我不必担心的事情?
I'm trying to make a Stack using an underlying linked list structure.
Maybe I'm wrong, but I'm having trouble with the remove() function.
int Stack::remove(){
node* victim = new node;
int popped;
popped = top->element;
victim = top;
top = victim->next;
delete victim;
return popped;
}
I'm getting glibc dectecting
double free or corruption (out);
Since I'm allocating new memory with victim, don't I have to delete victim, or is that something I don't have to worry about?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一堆很像一堆正在清洗并叠放在一起的盘子。即第一个输入最后一个输出(FILO 数据类型)。也就是说,如果您的堆栈读入 2, 7, 8,那么它将显示为:
8
7
2
也就是说,首先将 2 放入堆栈中,然后是 7,然后是 8。如果您想删除或弹出堆栈中你需要移动头部指针。你的代码对我来说看起来有点奇怪......
A stack is much like a bunch of dishes that are being washed and set on top of one another. That is the first one in is the last one out (FILO data type). That is if your stack read in 2, 7, 8 then it would appear as :
8
7
2
That is first the 2 is placed in the stack, followed by the 7 and then by the 8. If you want to remove or pop the stack you need to move the head of the pointer. Your code looks a bit strange to me...
没有理由像处理
victim
那样在remove()
方法中分配堆内存。你想要的是:There's no reason to allocate heap memory in a
remove()
method as you are doing withvictim
. What you want is:您不需要为
受害者
分配节点。只需将堆栈顶部分配给它,如果它不为 null,则将 top 设置为其next
指针,然后从中检索值>受害者
,然后解除分配受害者
。这实际上并不是损坏,而是内存泄漏 - 您正在分配一个节点,然后使用
victim = top;
覆盖该指针,从而失去对刚刚分配的内存的跟踪。You don't need to allocate a node for
victim
. Just assign the top of the stack to it and, if it's notnull
, settop
to itsnext
pointer, retrieve the value fromvictim
, and then deallocate thevictim
.It's not actually a corruption, but a memory leak - you are allocating a node, and then override that pointer with
victim = top;
thus losing track of just allocated memory.