I'm trying to import information from a file to a struct, but when I'm using malloc the program stop running. I've done similar functions before, I don't know why is not working.
This is my reading file function:
void ler_fich_salas(List_sala sala)
{
FILE *fich;
List_sala l;
char linha[10];
fich = fopen("fich_salas.txt","r");
l = l->next;
if (fich == NULL)
{
return;
}
else
{
/*ou l=l->next*/
while (!feof(fich))
{
printf("A");
fgets(linha, 10, fich);
printf("Z");
printf("%s",linha);/*testar se le bem no fich*/
printf("B");
free(l->nome_sala);
l->nome_sala = (char *)malloc(TAM*sizeof(char));
printf("C");
strcpy(l->nome_sala, strtok(linha,"\n"));
printf("D");
l = l->next;
}
}
fclose(fich);
}
and this is my struct:
typedef struct Sala_node *List_sala;
typedef struct Sala_node
{
char *nome_sala;
List_sala next;
}Cada_sala;
Any help would be appreciated! Thanks in advance.
1 Answer 1
List_sala l;
/* SNIP */
l = l->next;
From the use of the -> operator, l must be a pointer type, which means you're hiding pointer types behind a typedef, which is a bad idea.
Even more problematic is that you haven't assigned it to point at anything in your logic, and so the pointer value points at gibberish. It's a miracle your program runs up until the call to free, let alone the statement after it that you claim is problematic, as that's trying to deallocate more gibberish (something that wasn't allocated using malloc) and then (yet again) dereference and assign to even more gibberish.
Either you've cut the wrong parts of your logic out to form an MCVE, rendering our ability to reproduce the issue impossible without filling in blanks (don't do that) or... my guess is that your book isn't working for you, as people who read decent books don't tend to have this kind of misunderstanding; believe me, I've been there! Please see this list to find a better book.
TAM?salaparameter. Is that intentional?freeon an unallocated value is your problem.feof().salawhat I do with thel, but it was also doing an error. Also I calledfreebecause I thought that I was using too much memory, but I was just giving it a try.