0

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);
    }

}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Marco
  • 161
  • 8

2 Answers2

3

You are allocating memory for the size of pointer-to structure, whereas you need to allocate memory for the size of the structure itself.

Change

  *lista=malloc(sizeof(t_nodo));

to

  *lista=malloc(sizeof(struct s_nodo));

Also, you're using wrong expression to allocate memory to word.

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

should be

(*lista)->word=malloc( (strlen(aux) + 1 );  //sizeof(char) == 1 in C

That said, please see Why is “while ( !feof (file) )” always wrong?

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

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?

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97