首页 > 解决方案 > 二维数组分配后的分段错误

问题描述

我有这个代码:

#include <iostream>
#include <math.h>

int main()
{
    int n,m,k,hours;
    std::cin >> n >> m >> k;
    hours = std::ceil(n * k / (float)m);
    int* checkers = new int[m];
    int** check = new int*[hours];
    for(int i(0); i < hours; i++)
        check[i] = new int[n];
    for(int i(0); i < n; i++)
        checkers[i] = (i + 1) % m;
    std::cout << check[0][0];

    return 0;
}

对于特定的输入数据20 4 1,当我尝试打印 check[0][0] 时,它会返回分段错误。但如果我这样替换int* checkers = new int[m];

#include <iostream>
#include <math.h>

int main()
{
    int n,m,k,hours;
    std::cin >> n >> m >> k;
    hours = std::ceil(n * k / (float)m);
    int** check = new int*[hours];
    for(int i(0); i < hours; i++)
        check[i] = new int[n];
    int* checkers = new int[m];
    for(int i(0); i < n; i++)
        checkers[i] = (i + 1) % m;
    std::cout << check[0][0];

    return 0;
}

它会回来malloc.c:2394: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.

我该如何解决?

PS 以输入为例3 1 1,一切正常。

标签: c++segmentation-faultmallocdynamic-memory-allocation

解决方案


您在使用元素时分配m了元素。checkersn

要分配和使用的元素数量应该匹配(分配n元素或使用m元素,根据您想要做什么)。

另请注意, 的内容new int[n]不会自动初始化,因此您不能依赖 的值check[0][0]


推荐阅读