[英]Read 2D array from file with dimensions given in the first line
I wrote a code to read 2D array of integers from file with dimensions given in the first line . 我编写了一个代码,从文件中读取第一行给出尺寸的2D整数数组。 while running it it gives me the following error : 在运行它时,出现以下错误:
* Error in `./shell': double free or corruption (out): 0x000000000144a0c0 * Aborted (core dumped) *`./shell'错误:两次释放或损坏(输出):0x000000000144a0c0 *已中止(核心已转储)
here is my code 这是我的代码
#include <stdio.h>
#include <stdlib.h>
int main(int argc , char* argv[])
{
FILE * fp;
char * line = NULL;
char * token ;
size_t len = 0;
ssize_t read;
int i;
int j ;
int flag = 0 ;
int row = 0 ;
int **matr ;
char cwd[1024];
getcwd(cwd, sizeof(cwd)) ;
char *matrix = malloc(strlen(cwd)+10);
// here but your file name
asprintf(&matrix,"%s%s",cwd,"/matrix");
fp = fopen(matrix, "r");
if (fp == NULL)
{
exit(EXIT_FAILURE);
}
while ((read = getline(&line, &len, fp)) != -1)
{
if(flag == 0)
{
token = strtok (line," ");
i = atoi(token);
token = strtok (NULL, " ");
if (token != NULL)
{
j = atoi(token);
}
printf("%d %d\n",i,j);
flag =1 ;
matr = (int**)malloc(i*sizeof(int*));
int e ;
for(e=0; e<=i; e++)
{
matr[e] = (int*)malloc(j*sizeof(int));
}
}
else if(row <i)
{
int col = 0 ;
token = strtok (line,"\t");
while (token != NULL && col<j)
{
matr[row][col] = atoi(token);
printf("%d ",matr[row][col]);
col++ ;
token = strtok (NULL,"\t");
}
printf("\n");
row++ ;
}
}
fclose(fp);
return 0;
}
any solution ? 有什么办法吗?
the posted code has a unrecoverable memory leak. 发布的代码具有无法恢复的内存泄漏。
the pointer matrix
is set to point to some allocated memory by a call to the malloc() function, 通过调用malloc()函数将指针matrix
设置为指向某些已分配的内存,
Then that pointer is overlayed by the call to asprintf() suggest either using sprintf() or replace the call to malloc()
with char *matrix = NULL;
然后,该指针被对asprintf()的调用覆盖,建议使用sprintf()或将对malloc()
的调用替换为char *matrix = NULL;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.