从 .txt 文件创建字符串列表

Create a list of string from a .txt file

我正在尝试创建一个从 .txt 文件中读取单词的字符串列表。我的代码只有在.txt文件包含少量单词时才有效,我不知道为什么,我认为这是我代码的内存分配问题。

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

}

你的编码风格导致了这个错误

(*lista)->word=malloc((strlen(aux+1))*sizeof(char));
                        //       ^
  1. 不要使用 sizeof(char) 因为它是 1 并且是强制性的,它只是帮助您忽略了这个问题。
  2. 使用更多的白色space,这样可以很容易地在你眼前区分标记。
  3. 在使用指针之前始终检查 malloc() 没有 return NULL

所以应该是

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

看看现在是不是很清楚,是吗?

您正在为指向结构的指针的大小分配内存,而您需要为结构本身的大小分配内存。

改变

  *lista=malloc(sizeof(t_nodo));

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

此外,您使用错误的表达式将内存分配给 word

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

应该是

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

也就是说,请看Why is “while ( !feof (file) )” always wrong?