二维数组分配后的分段错误

Segmentation fault after 2-d array allocation

我有这个代码:

#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 这样的特定输入数据,当我尝试打印支票 [0][0] 时 return 出现分段错误。 但是如果我像这样替换 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;
}

会returnmalloc.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.

我该如何解决?

P.S。输入,例如3 1 1,一切正常。

您在使用 n 个元素时为 checkers 分配了 m 个元素。

分配和使用的元素数量要匹配(分配n个元素或使用m个元素,根据你的需要而定)。

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