Create string lists

3

I'm trying to copy the words of 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 an error in the assignment of the memory. I do not understand where I'm 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);
    }
}
    
asked by Marco 04.02.2016 в 17:59
source

2 answers

1

As you rightly say, there is an error in memory allocation, specifically in the second malloc within the function agregar :

(*lista)->palabra=malloc((strlen(aux+1))*sizeof(char));

The problem is in the strlen where you do strlen(aux+1) , and what you should do is strlen(aux)+1 . I have not worked with C pointers for a long time now, so maybe I'm wrong, but if I remember correctly: when doing aux+1 you're really trying to access the next memory position from aux , and then the result of strlen(aux+1) is not what you expect, creating memory problems at runtime.

By correcting that line to:

(*lista)->palabra=malloc((strlen(aux)+1)*sizeof(char));

the program runs smoothly.

    
answered by 04.02.2016 / 21:01
source
0

The error is on the line:

(*lista)->palabra=malloc((strlen(aux+1))*sizeof(char));

of your method add:

void agregar (t_nodo*lista,char *aux)
{
    if(*lista==NULL)
    {
        *lista=malloc(sizeof(t_nodo));
        //(*lista)->palabra=malloc((strlen(aux+1))*sizeof(char)); //Error!
        (*lista)->palabra=malloc(strlen(aux)+1); // Corrige error.
        strcpy((*lista)->palabra,aux);
        (*lista)->sig=NULL;

    }
    else agregar(&(*lista)->sig,aux);
}

To accommodate memory you only need: malloc( ) , it is not necessary *sizeof(char)

    
answered by 04.02.2016 в 22:19