我一直遇到段错误,不知道为什么
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
分配的每个内存 space。在您的情况下,您还应该 free(M->m)
您的 makeMatrix
函数有误。执行makeMatrix
时,参数M
是一个local变量。因此,对 M
的任何更改在函数结束时 不 可见。结果 test
在传递给 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);
就足够了。
此代码用于制作和打印矩阵,但我不确定为什么会出现段错误,这是因为我没有释放内存,如果是这样我该如何释放它?
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
分配的每个内存 space。在您的情况下,您还应该 free(M->m)
您的 makeMatrix
函数有误。执行makeMatrix
时,参数M
是一个local变量。因此,对 M
的任何更改在函数结束时 不 可见。结果 test
在传递给 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);
就足够了。