我编写的程序将整数向量数组转换为邻接矩阵,即(n + 1)x(n + 1)数组。当我在写入的函数中执行此操作时,设置int **的动态内存分配似乎会覆盖整数向量的n + 1和n + n元素。
int** makeAdjMatrix(IntVec* Vec, int length) { //allocates a new nxn array
printf(" madm test %d \n" , Vec[1]->data[6]);
//confirming that the intvec entered okay
int** new;
new = (int**)malloc(length+1*length+1*sizeof(int*))
printf(" madm test %d \n" , Vec[1]->data[6]);
// confirming that something happenend to the intvec
for (int i = 0; i <= length + 1; i++) {
new[i] = (int*)malloc(length + 1*sizeof(int));
}
for (int i = 1; i <= length+1; i++) {
for (int j = 1; j <= length+1; j++) {
new[i][j] = 0;
}
}
通常为矢量数据结构中的所有元素输出除n + 1及以上的元素。在这种情况下,n为5。
上面的代码打印
测试1
测试33
段错误 (因为数组中没有33rd索引,代码稍后会引用)
这个内存耗尽了吗?我如何覆盖堆上先前分配的数组?这可能有点模糊,这是我的第一个问题。顺便说一句,这只发生在矢量数组重复相同的输入时。
我有多糟糕?