c++ - 二维数组分配后的分段错误
问题描述
我有这个代码:
#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
,一切正常。
解决方案
您在使用元素时分配m
了元素。checkers
n
要分配和使用的元素数量应该匹配(分配n
元素或使用m
元素,根据您想要做什么)。
另请注意, 的内容new int[n]
不会自动初始化,因此您不能依赖 的值check[0][0]
。
推荐阅读
- scala - 如何从包含任何数字的RDD中获取行数
- r - 如何从单独的 ui-xxx-xxx.R 文件呈现 UI
- css - 样式化的组件不适用于层次选择器
- php - Laravel - 在 SQL 数据库中存储 JSON 响应(通过 Guzzle)
- c++ - 如何将静态数组初始化为 C++ 函数中的某个值?
- reactjs - 无法使用 fetch() 将选项选项加载到 SelectInput 中
- python-3.x - 如何在 python3 中发送 http 2.0 伪标头
- java - java servlet 出现 404 错误。看不到html文件
- c# - 增加 DataGridView 中水平网格线的高度?
- python - 使用 einsum 的张量接触