c++ - 在 C++ 中使用 2D vector 时出现明显的内存泄漏

标签 c++ gdb

我决定将 C++ 2D vector 用于应用程序。在测试一些代码时,我遇到了 bad alloc错误。我读到这可能是由于内存不足造成的,所以我通过调用 malloc_stats 来调查程序的内存使用情况。在 gdb 的不同步骤中起作用。
虽然我不确定我是否完全理解函数的输出,但它似乎表明内存泄漏。

我试图在下面的短代码中总结问题:

#include <vector>
#include <iostream>

using namespace std;

vector<vector<double>> get_predictions(){
    vector<vector<double>> predictions;
    for(int i = 0; i < 10; i++){
        vector<double> new_state;
        new_state.push_back(600);
        new_state.push_back(450);
        new_state.push_back(100);
        new_state.push_back(200);
        predictions.push_back(new_state);
    }
    return predictions;
}

int main()
{
    cout << "start" << endl;

    // time loop
    for(int i = 0; i < 10; i++){
        auto predictions = get_predictions();
        // code that uses the latest predictions
    }

    cout << "end" << endl;
    return 0;
}

现在,如果我调用 malloc_stats()在“开始”行,输出类似于:
Arena 0:
system bytes     =     135168
in use bytes     =      74352
Total (incl. mmap):
system bytes     =     135168
in use bytes     =      74352
max mmap regions =          0
max mmap bytes   =          0

在“结束”步骤,函数给出:
Arena 0:
system bytes     =     135168
in use bytes     =      75568
Total (incl. mmap):
system bytes     =     135168
in use bytes     =      75568
max mmap regions =          0
max mmap bytes   =          0

“使用中的字节数”字段明显增加。

这真的意味着持有更多分配的内存吗?

如果是这样,为什么?一旦不同的 vector 超出范围,分配的内容不应该被释放吗?

那么,如何避免这种内存问题呢?

非常感谢

最佳答案

由于评论中的建议,我放弃了 malloc_stats,它的行为似乎不像我预期的那样,并在我的代码上试用了 Valgrind。

Valgrind 确认上面的玩具示例中没有泄漏。

关于我的主要应用程序,它是一个在 ARM 上运行的程序。由于我不知道的原因,基本 Valgrind 实现是通过 apt install valgrind 获得的。没有输出与内存泄漏有关的行。我不得不从 Valgrind 网站上的可用资源重新编译它。问题必须来自特定于架构的特殊性?

作为旁注,我的应用程序还使用了 CUDA 代码,这意味着 Valgrind 输出中有许多误报。

关于c++ - 在 C++ 中使用 2D vector 时出现明显的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61780670/

相关文章:

c++ - 什么时候应该在字符数组上使用 std::string?

c++ - 在对象中存储包含 std::placeholders 的 std::function

c++ - 从 C++ 函数返回 char 数组到 tcl

linux - 如何使用 gdbserver 进行远程调试?

设置 "conditional"断点时 Xcode 调试器很慢?

c++ - 为什么我的程序给出 "NULL used in arithmetic"

c++ - 如何排序 vector<vector<int>>

iphone - 为什么这在 XCode 调试窗口中不起作用 "po [myNsDateComponent weekday]"

c++ - 使用 minidumps 和 GDB 分析 mingw 编译的可执行文件的崩溃?

c - 如何使用gdb调试越界?