C++ 3D vector 更新 malloc 不正确的校验和

标签 c++ vector memory-management malloc

我只是从 Python 学习 C++。我对内存管理概念很陌生,我很难理解我的方法出了什么问题。我的目标是从用户输入中获取数字列表并将它们放在 NxN vector 图中。每个节点都是一个 vector 存储 {input_number, row_index, col_index, 0} .有人可以解释这里具体出了什么问题吗? for 循环似乎到达第二行然后出错。

源代码:

int N;
cin >> N;
int total = N * N;
vector<vector<vector<int>>> graph (N, vector<vector<int>>(N, vector<int>(4)));
int col = 0; int row = 0; int startcol; int startrow;
for (int i = 0; i < total; i++) { 
    int num;
    cin >> num;
    graph[row][col] = vector<int>({num, row, col, 0});
    if (num == 1) {
        startrow = row;
        startcol = col;
    }
    if (col < N) {
        col++;
    }
    else {
        col = 0;
        row++;
    }
}
int result = search(graph, startrow, startcol, N);

错误:

a.out(7393,0x7fffc20433c0) malloc: *** error for object 0x100300138: incorrect checksum for freed object - object was probably modified after being freed.

我最终使用了一种不同的方法,即嵌套到 for 循环并更新节点的每个元素,一次一个。我觉得这个问题与覆盖 graph[row][col] = vector<int>({num, row, col, 0}) 行中的整个节点 vector 有关。但这在 Python 中会很好地工作(可能是因为它处理 bg 中的所有内存管理),所以我在这里不明白为什么我不能用新整数的 N vector 替换 0 的 N vector 。

最佳答案

在您当前的逻辑中 col < N访问graph[row][col]后检查完成.这意味着 col变得等于 N , 尝试访问 graph[0][N]只有在那之后重置col .

所以你必须检查col在访问 graph 之前或之后检查“if (col < N-1)”。

关于C++ 3D vector 更新 malloc 不正确的校验和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51889678/

相关文章:

c++ - 错误 : '_mm512_loadu_epi64' was not declared in this scope

c++ - 通过迭代器删除 vector 中的元素无效,但它不会崩溃

c++ - C++11 是否允许 vector<const T>?

c - 如何在 C 中使用一个引用创建多个内存块

c# - 如何强制通用应用程序释放内存?

iphone - 我需要显式分配我的 NSNumber 吗?

c++ - 在 C++ 中创建类型列表组合

Android NDK r10: std::string 尚未声明

c++ - vector 中元素的位置

c++ - 返回 std:vector 与 std::async c++11