Search code examples
cstringpointersmallocdynamic-memory-allocation

Create a list of string from a .txt file


I'm trying to create a list of string reading the words from a .txt files. My code only works when the .txt files contains a small amount of words and i can't figure out why, I think it's a problem of memory allocation of my code.

#include <stdio.h>
#include <stdlib.h> struct s_nodo {
    char* word;
    struct s_nodo*sig; }; typedef struct s_nodo* t_nodo;

void add (t_nodo*,char*); void print(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);
        add(&lista,aux);

    }
     print(lista);
    return 0; }



void add (t_nodo*lista,char *aux) {

    if(*lista==NULL)
    {
        *lista=malloc(sizeof(t_nodo));
        (*lista)->word=malloc((strlen(aux+1))*sizeof(char));
        strcpy((*lista)->word,aux);
        (*lista)->sig=NULL;

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

}

void print (t_nodo lista) {
    if(lista!=NULL)
    {
        printf("-%s-",lista->word);
        print(lista->sig);
    }

}

Solution

  • Your coding style leads to this mistake right here

    (*lista)->word=malloc((strlen(aux+1))*sizeof(char));
                            //       ^
    
    1. Don't use sizeof(char) because it's 1 and that's mandatory, it just helped you overlook this problem.
    2. Use more white space, that will separate tokens easily before your eyes.
    3. Always check that malloc() did not return NULL before using the pointer.

    So it should be

    (*lista)->word = malloc(strlen(aux) + 1);
    

    see how it's clear now, isn't it?