[英]I keep getting a seg fault not sure why
這段代碼是用來制作和打印一個矩陣,但我不確定為什么我會出現段錯誤,這是因為我沒有釋放內存,如果是這樣,我將如何釋放它?
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;
}
首先,必須始終檢查 malloc 是否成功分配了內存。 所以在第一次調用malloc
,你應該這樣寫:
if(!M)
{
printf("malloc failed to allocate memory for M");
return;
}
等等。 此外,您應該釋放使用malloc
分配的每個內存空間。 在你的情況下,你也應該free(M->m)
你的makeMatrix
函數是錯誤的。 參數M
是makeMatrix
執行時的局部變量。 因此,當函數結束時,對M
任何更改都不可見。 由於在傳遞給printMatrix
時未初始化結果test
導致失敗,然后指針被取消引用。
解決方案是從函數中按值返回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);
就足夠了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.