我写了一段代码来处理各种参数(文件,动态二维数组,将指针传递给函数等),所以不要介意某些段落似乎没用。 在运行时,如果我输入了3行以上,则程序崩溃,并且终端显示“ Double free or destroy(out)”,然后创建了核心转储。该错误应在foo2中的fclose(fp)上发生。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void foo1(int *);
void foo2(int*,int,int**,FILE*);
void readfoo(FILE *, int **, int);
int main(void)
{
FILE *fp;
int **a, i, j, r, c, *pr, *pn, *pc;
pc = &c;
pr = &r;
foo1(pr);
a = malloc(r*sizeof(int));
foo2(pc,r,a,fp);
if((fp = fopen("column.txt", "r")) == NULL)
{
fprintf(stderr, "Error, can't open \"column.txt\"");
exit(1);
}
for(i=0;i<r;i++)
{
fscanf(fp,"%d", &c);
for(j=0; j<c; j++)
{
fprintf(stdout, "insert line %d column %d -> ", i+1, j+1);
fscanf(stdin, "%d", &a[i][j]);
}
}
if(fclose(fp) != 0)
{
fprintf(stderr, "Error, can't close \"column.txt\"");
exit(1);
}
readfoo(fp,a,r);
remove("column.txt");
return(0);
}
void foo1(int *r)
{
fprintf(stdout, "how many lines ? -> ");
fscanf(stdin, "%d", r);
}
void foo2(int *c, int r, int **a, FILE *fp)
{
int i,j, act_c;
if((fp = fopen("column.txt", "w")) == NULL)
{
fprintf(stderr, "Error, can't open \"column.txt\"");
exit(1);
}
for(i=0;i<r;i++)
{
fprintf(stdout, "how many columns for line %d? -> ", i+1);
fscanf(stdin, "%d", c);
fprintf(fp,"%d\n", *c);
a[i] = malloc((*c)*sizeof(int));
}
if(fclose(fp) != 0)
{
fprintf(stderr, "Error, can't close \"column.txt\"");
exit(1);
}
}
void readfoo(FILE *fp, int **a, int r)
{
int c, i, j;
fprintf(stdout, "printing the matrix... \n");
if((fp = fopen("column.txt", "r")) == NULL)
{
fprintf(stderr, "Error, can't open \"column.txt\"");
exit(1);
}
for(i=0;i<r;i++)
{
fscanf(fp,"%d", &c);
for(j=0; j<c; j++)
{
fprintf(stdout, "%d ", a[i][j]);
}
fprintf(stdout, "\n");
}
if(fclose(fp) != 0)
{
fprintf(stderr, "Error, can't close \"column.txt\"");
exit(1);
}
}
答案 0 :(得分:1)
在main()
中,您可以
a = malloc(r*sizeof(int));
那应该是错误的
a = malloc(r*sizeof(int *));
如果您为a[i]
分配值,则会调用UB,这可能是崩溃的真正原因