c - C:### 处的堆块已修改为 ### 过去请求的大小为 ###
问题描述
所以我将一个二维动态数组存储到一个矩阵结构中:
struct Matrix {
int ncol;
int nrow;
double **mat;
};
typedef struct Matrix Matrix;
然后我有一个函数,它从二维数组中获取内容并将其存储到矩阵中:
// Initializes matrix mat whose values are the passed in 2D array
// Made Matrix **mat a double pointer so that I can initialize the Matrix *pointer from Main
void matrix_initializeFromArray(Matrix **mat, int nrow, int ncol, double array[][ncol]) {
(*mat) = (Matrix*) malloc(sizeof(Matrix*));
(*mat)->mat = (double**) malloc(nrow*sizeof(double*));
for(int i = 0; i < nrow; i++) {
(*mat)->mat[i] = (double*) malloc(ncol*sizeof(double*));
for(int j = 0; j < ncol; j++) { // intialize all values to array values
(*mat)->mat[i][j] = array[i][j];
}
}
(*mat)->ncol = ncol;
(*mat)->nrow = nrow;
}
这是矩阵的析构函数:
// Destructor
void matrix_destructor(Matrix **mat) {
for(int i = 0; i < (*mat)->nrow; i++) {
free((*mat)->mat[i]);
}
free((*mat)->mat);
free(*mat);
}
一个小例子如下:
void main() {
Matrix *temp;
double array[1][1];
array[0][0] = 34;
matrix_initializeFromArray(&temp, 1, 1, array);
matrix_print(temp);
matrix_destructor(&temp);
}
此代码在我的 Linux Ubuntu 中的 gdb 和 valgrind 上正常执行,但由于某种原因,它在我在 Windows 上运行时会产生此错误。
warning: HEAP[a.exe]:
warning: Heap block at 00B51710 modified at 00B5171C past requested size of 4
我在 Windows 上运行了 gdb,它出现在第一个循环的析构函数中的这一行:free((*mat)->mat[i]);
有什么帮助吗?
解决方案
我已经简化了你的代码,matrix_print 丢失问题出在 malloc 当你分配一些东西时你会得到一个指向内存的指针,例如
malloc(sizeof(double));
返回一个指向可以存储双精度的内存区域的指针,所以double *
malloc(sizeof(double*));
返回一个指向内存的指针,它可以存储指向双精度的指针,所以双 **`
#include <stdio.h>
#include <stdlib.h>
struct Matrix {
int ncol;
int nrow;
double **mat;
};
typedef struct Matrix Matrix;
void matrix_initializeFromArray(Matrix *mat, int nrow, int ncol, double array[][ncol]) {
mat->ncol = ncol;
mat->nrow = nrow;
mat->mat = malloc(nrow * sizeof(double*));
for(int i = 0; i < nrow; i++) {
mat->mat[i] = malloc(ncol*sizeof(double));
for(int j = 0; j < ncol; j++) { // intialize all values to array values
mat->mat[i][j] = array[i][j];
}
}
}
void matrix_wipe(Matrix *mat) {
for(int i = 0; i < mat->nrow; i++) {
free(mat->mat[i]);
}
free(mat->mat);
}
int main(void) {
Matrix temp;
double array[1][1];
array[0][0] = 34;
matrix_initializeFromArray(&temp, 1, 1, array);
matrix_wipe(&temp);
return 0;
}
推荐阅读
- python - 尝试使用 selenium python 获取下拉菜单的长度时元素不存在错误
- python - 当 QuerySet 为空时,如何找到 RelatedManager 管理的类?
- python - 为什么我的 for 循环实际上没有循环?我没有中断功能,并希望它循环但它没有
- c# - 生成 Swagger/Autorest API 客户端时出现语义冲突
- python - python中针对自定义异常的错误处理
- java - 在 IDEA 上运行教程项目“table-walkthrough”时遇到多个问题
- ios - iOS FBSDK 图形请求失败,“code”:100,“error_subcode”:facebook 响应中的 33
- javascript - 如果不在视口视图中,如何从 DOM 中隐藏元素
- salesforce - salesforce lwc - 有线适配器无法将跟踪变量声明为参数
- python - python光标列出条件超过条目