c++ - C++ 中的内存泄漏 (Valgrind)
问题描述
我以最少的方式实现堆栈。在这个程序中,我从 valgrind 得到一个错误。push() 和 main() 函数有问题。当我添加删除 st; 对于 push() 函数,我得到更多错误。我通过 valgrind ./a.out 检查它。抱歉,代码太长了。我还为堆栈编写了其余的函数。但是它们没有错误,我把那些留在代码中可能有错误的地方。
#include <cstring>
#include <iostream>
struct Stack {
int data;
int min;
Stack* next;
};
void Push(Stack** top, int n) {
Stack* st = new Stack();
st->data = n;
if (*top == NULL) {
*top = st;
(**top).min = n;
} else {
st->min = ((n <= (**top).min) ? n : (**top).min);
st->next = *top;
*top = st;
}
std::cout << "ok" << std::endl;
}
void Pop(Stack** top) {
if (*top != NULL) {
std::cout << (**top).data << std::endl;
*top = (*top)->next;
} else {
std::cout << "error" << std::endl;
}
}
int main() {
Stack* top = nullptr;
int m;
std::cin >> m;
std::string str;
for (int i = 0; i < m; ++i) {
std::cin >> str;
if (str == "push") {
int value;
std::cin >> value;
Push(&top, value);
}
if (str == "pop") {
Pop(&top);
}
}
delete top;
}
解决方案
当你只是delete top
,你破坏它(在你的情况下它什么都不是,但如果有兴趣,你可以分散自己的注意力来阅读关于析构函数的内容)并释放分配给top
. 但是,您实际上还想要delete
top->next
, top->next->next
(如果存在)等。修补程序:
while (top) { // same as "while (top != nullptr) {"
Stack* next = top->next; // we can't use `top` after we `delete` it, save `next` beforehand
delete top;
top = next;
}
现在,关于更一般的事情。该课程教你一些非常古老的 C++(几乎只是普通的 C;尽管这里的 C 也很糟糕)。至少,你的整体Push()
可以被替换(感谢左值引用(Type&
)std::min
和聚合初始化):
void push(Stack*& top, int n) {
top = new Stack{n, std::min(n, top ? top->min : n), top};
std::cout << "ok\n";
}
我是 C++ 编程的新手。我以前用 Python 写
好工作。可悲的是,这样的教学表明 C++ 太古老了,太可怕了。
编辑
这是 Push 中的一个新内容,因此 Pop 中应该很可能有一个 delete
没错(感谢@molbdnilo)。您应该delete
pop
ped 元素而不是仅仅泄漏它们。
推荐阅读
- python - 使用python从Sharepoint文件夹中检索.xlsx文件列表
- sql - 根据那里的顺序标记行(连续值)
- python - Pandas DataFrame:用数字计算单元格的数量
- macos - 获取 WebStorm 上的所有代码完成选项
- python - 标签编码器 - 使用 Inverse_transform 函数
- r - 订购 ggplot 轴和颜色
- react-native - 有没有办法在反应原生路由器通量中隐藏父标签栏?
- terraform - 使用 SQL FO 组的专用链接并使用 Terraform 配置基础架构
- javascript - 创建 MERN 堆栈应用程序时出现代理错误和 webpack 错误
- java - 使用 SpringServices 作为 SpringData