c++ - 为什么所有指针都没有被释放?
问题描述
我正在使用链表进行堆栈数据结构实现,构建 destroyStack() 函数,一旦我完成使用堆栈类,我可以释放所有分配的内存,因为我执行 main 我希望在 destroyStack() 之后释放所有指针被调用。
class Stack{
private:
int size;
typedef struct Node{
stackType data;
struct Node *last;
} Node;
Node *top;
public:
Stack(){
size = 0;
top = NULL;
}
void push(stackType element){
Node *temp = new Node();
if (!temp)
throw invalid_argument("heap overflow");
if (element != '\0'){
temp->data = element;
temp->last = top;
top = temp;
size++;
}
else{
throw invalid_argument("invalid element");
}
}
stackType pop(){
if (empty())
throw invalid_argument("this is an empty stack");
Node *temp = new Node();
stackType element = top->data;
temp = top;
top = top->last;
temp->last = NULL;
delete(temp);
size--;
return element;
}
void destroyStack(){
Node *temp = top;
while (top != NULL){
top = top->last;
delete(temp);
temp = top;
}
}
};
int main(){
Stack stack;
stack.push(100);
stack.push(90);
stack.push(80);
stack.printStack();
for (int i = 0; i < 3; i++)
cout << stack.pop() << endl;
stack.destroyStack();
return 0;
}
当我使用 valgrind 检查是否有任何泄漏时,我发现了此消息。
==53372== HEAP SUMMARY:
==53372== in use at exit: 48 bytes in 3 blocks
==53372== total heap usage: 8 allocs, 5 frees, 73,824 bytes allocated
==53372==
==53372== Searching for pointers to 3 not-freed blocks
==53372== Checked 116,952 bytes
那么有什么想法可以在我使用破坏功能后编辑我的代码以释放所有块?
解决方案
正如评论中已经提到的@AlanBirties,问题出Node *temp = new Node();
在你的pop()
函数中。
- 你必须为 each 做一个
delete
,new
所以这是一个你不会删除的块。 - 但是,您甚至不需要那个新节点……因为该指针的目的是保存最后一个已经存在的顶部节点,而不是新节点。
// Problematic code:
Node *temp = new Node();
temp = top; // previous new node is not freed and never used
// Correct code:
Node *temp = top; // no useless memory allocated
你已经这样做了destroyStack()
;)
推荐阅读
- php - php $_POST 的奇怪问题
- javascript - 检查电子邮件已经存在于数据库中
- ios - swift如何仅在数据完全存储在核心数据中后才调用数据数据获取功能?
- django - 我想根据评分过滤我的产品,我该怎么做?
- android - “应用程序未安装”错误,尽管 apk 使用与以前版本 apk 签名的相同上传密钥进行签名
- scalardb - scalardb 调试打印显示 `?` 的值。有错误吗?
- list - 带有 Toggle 和 NavigationLink 的 SwiftUI onDelete 列表
- angular - 大资产文件夹的成本
- .net - 如何在 VB.net 中使用补丁方法路径参数
- powerbi - How can I write DAX to aggregate total time?