I need to make a program that, at first, read a matrix from a text file and put it on memory. I was able to do so, but when I try to close files with matrix with 4 lines or more it gives the error: * Error in `./threads': corrupted double-linked list: 0x0000000001b4e240 * the code to read the file is:
void leitura_matriz1 ()
{
char linha_s[MAX_LINHA];
char *buffer;
// leitura da primeira matriz
FILE * matriz1_file;
matriz1_file = fopen ("in1.txt","r");
if (matriz1_file == NULL)
{
printf ("Erro na abertura do arquivo\n");
exit(1);
}
// número de linhas
fgets(linha_s, MAX_LINHA, matriz1_file);
buffer = strtok(linha_s, " =");
buffer = strtok(NULL, " =");
linhas_mat1 = atoi(buffer);
// número de colunas
fgets(linha_s, MAX_LINHA, matriz1_file);
buffer = strtok(linha_s, " =");
buffer = strtok(NULL, " =");
colunas_mat1 = atoi(buffer);
// aloca espaço para a matriz
matriz1 = (int**) malloc(linhas_mat1 * sizeof(int));
if (matriz1 == NULL)
{
printf("erro memória");
exit(1);
}
int lin, col;
for (lin = 0; lin < linhas_mat1; lin++)
{
matriz1[lin] = (int*) malloc(colunas_mat1 * sizeof(int));
if (matriz1[lin] == NULL)
{
printf ("erro memória 2");
exit(1);
}
}
// lê os valores do arquivo e coloca na matriz em memória
for (lin = 0; lin < linhas_mat1; lin++)
{
fgets(linha_s, MAX_LINHA, matriz1_file);
buffer = strtok(linha_s, " ");
for (col = 0; col < colunas_mat1; col++)
{
matriz1[lin][col] = atoi(buffer);
buffer = strtok(NULL, " ");
}
}
fclose (matriz1_file);
}
the file format is this:
LINHAS = 4
COLUNAS = 3
5 5 5
5 5 5
5 5 5
5 5 5
LINHAS is lines and COLUNAS columns I have never got error in closing a file when it is still opened. and it only happens if the file has more than 3 lines (4 or more lines). someone knows what it might be?