這段代碼是用來製作和打印一個矩陣,但我不確定為什麼我會出現段錯誤,這是因為我沒有釋放內存,如果是這樣,我將如何釋放它?
void printMatrix(struct Matrix *M){
struct Matrix *temp = M;
for(int i=0; i< temp->rows;i++){
for(int j=0; j< temp->cols;j++){
printf("%.f",getVal(temp,i,j));
}
printf("\n");
}
}
void makeMatrix(struct Matrix *M, int row, int col, int num){
M = malloc(sizeof(struct Matrix));
M->rows=row;
M->cols=col;
M->m =malloc(100*sizeof(double)*M->rows*M->cols);
for(int i=0; i<M->rows;i++){
for(int j=0; j<M->cols;j++){
setVal(M,i,j,num);
}
}
free(M);
}
int main(int argc, char const *argv[]) {
struct Matrix *test;
makeMatrix(test,10,10,10);
printMatrix(test);
return 0;
}
你的makeMatrix
功能錯了。參數在執行時M
是一個局部變量makeMatrix
。Thereofre任何改變M
都沒有看到當函數結束。由於 resulttest
在傳遞給printMatrix
導致失敗時未初始化,因此指針被取消引用。
解決方案是M
按值從函數返回。
struct Matrix *makeMatrix(int row, int col, int num){
struct Matrix *M = malloc(sizeof(struct Matrix));
if (!M) return NULL;
M->rows=row;
M->cols=col;
M->m =malloc(100*sizeof(double)*M->rows*M->cols);
if (!M->m) {
free(M);
return NULL;
}
for(int i=0; i<M->rows;i++){
for(int j=0; j<M->cols;j++){
setVal(M,i,j,num);
}
}
return M;
}
用法:
struct Matrix *test = makeMatrix(10,10,10);
此外,malloc(100*sizeof(double)*M->rows*M->cols);
看起來有點浪費,因為它消耗的內存比所需的多 100 倍。我很確定malloc(sizeof(double)*M->rows*M->cols);
這就足夠了。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句