I am trying to copy the words from a file .txt
into a linked list. I wrote something but what happens is that the program closes in a moment, as if there was a memory allocation error. I don't understand where I am going wrong.
#include <stdio.h>
#include <stdlib.h>
struct s_nodo
{
char* palabra;
struct s_nodo*sig;
};
typedef struct s_nodo* t_nodo;
void agregar (t_nodo*,char*);
void imprimir(t_nodo);
int main()
{
char aux[30];
t_nodo lista=NULL;
FILE*fd;
fd=fopen("c:\\texto.txt","r");
while(!feof(fd))
{
fscanf(fd,"%s",aux);
agregar(&lista,aux);
}
imprimir(lista);
return 0;
}
void agregar (t_nodo*lista,char *aux)
{
if(*lista==NULL)
{
*lista=malloc(sizeof(t_nodo));
(*lista)->palabra=malloc((strlen(aux+1))*sizeof(char));
strcpy((*lista)->palabra,aux);
(*lista)->sig=NULL;
}
else agregar(&(*lista)->sig,aux);
}
void imprimir (t_nodo lista)
{
if(lista!=NULL)
{
printf("-%s-",lista->palabra);
imprimir(lista->sig);
}
}
As you say, there is an error in memory allocation, specifically in the second one
malloc
inside the functionagregar
:The problem is
strlen
where you dostrlen(aux+1)
, and what you should do isstrlen(aux)+1
. It's been a long time since I worked with pointers in C so I may be wrong, but if I remember correctly: when doingaux+1
you are actually trying to access the next memory location fromaux
, and then the result ofstrlen(aux+1)
is not what you expect, creating problems memory at run time.By correcting that line to:
the program runs without problems.
The error is in the line:
of your method add:
To allocate memory you only need :
malloc( )
, it is not necessary*sizeof(char)