gpt4 book ai didi

c - 正常 block 后检测到堆损坏(#63)

转载 作者:行者123 更新时间:2023-11-30 21:17:12 29 4
gpt4 key购买 nike

我必须将 2 个静态矩阵发送到分配动态矩阵的函数,将矩阵 1 乘以矩阵 2,并返回新矩阵的地址。请注意,COMM 很常见。

我尝试删除 free_matrix 行,它工作正常。

void main()
{
int mat1[ROW1][COMM]={0},mat2[COMM][COL2]={0};
int** newmat=NULL;
//here i randomize the matrixes
newmat=allocate_dyn_and_mult(mat1,mat2); //newmat is now address
//of allocated dynamic after multiplied matrix.
printf("result:\n");
print_dyn_matrix(newmat,ROW1,COL2); //prints new mat;
free_matrix(newmat,ROW1); //without this line it works fine.
}



int ** allocate_dyn_and_mult(int mat1[ROW1][COMM],int mat2[COMM][COL2])
//return pointer to allocated memory in the size of row1 * col2
{
int i;
int **mat;
mat=(int**)calloc((ROW1),sizeof(int*));
for (i=0;i<COL2;i++)
{
mat[i]= (int*)calloc((COL2),sizeof(int));
}
matmult(mat1,mat2,mat); //mat will receive the multiply of mat1,mat2.
return mat;
}

释放内存

void free_matrix (int **c, int n)
{
int i;
for (i=0; i<n; i++)
free (c[i]);
free (c);
}

最佳答案

首先为 ROW1 分配内存指针与

mat=(int**)calloc((ROW1),sizeof(int*));

但是循环使用了不同的长度

for (i=0;i<COL2;i++)
{
mat[i]= (int*)calloc((COL2),sizeof(int));
}

哪里mat[i]将在 ROW1 < COL2 时分配的内存之外写入,导致堆损坏。循环应该是

for (i=0;i<ROW1;i++)

关于c - 正常 block 后检测到堆损坏(#63),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45894032/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com