List 在while循环中创建链表时出现问题。在第二次运行循环中获取运行时错误

List 在while循环中创建链表时出现问题。在第二次运行循环中获取运行时错误,list,while-loop,linked-list,strncpy,List,While Loop,Linked List,Strncpy,我正在编写一个程序,将文本的每一行放在链接列表的一个节点中。我想为文本中的每一行创建一个新节点。程序在while循环的第二次运行期间崩溃。经过一些测试,我认为它与strncpy函数有关,但不确定。我哪里出了问题 #include <stdio.h> #include <stdlib.h> #define MAXBUF 50 struct node { char data[MAXBUF]; struct node *next; }; int main(v

我正在编写一个程序,将文本的每一行放在链接列表的一个节点中。我想为文本中的每一行创建一个新节点。程序在while循环的第二次运行期间崩溃。经过一些测试,我认为它与strncpy函数有关,但不确定。我哪里出了问题

#include <stdio.h>
#include <stdlib.h>
#define MAXBUF 50

struct node
{
    char data[MAXBUF];
    struct node *next;
};

int main(void)
{
    FILE *f;
    f = fopen("text.txt", "r");
    if (f == NULL) exit("ERROR\n");

    struct node *root = NULL;
    struct node *pointer = NULL;

    root = malloc(sizeof(struct node));
    pointer = root;

    char buf[MAXBUF];
    while(fgets(buf, MAXBUF, f) != NULL)
    {
        strncpy(pointer->data, buf, MAXBUF);
        pointer->next = malloc(sizeof(struct node));
        pointer->next = NULL;
        pointer = pointer->next;
    }
    fclose(f);
}
#包括
#包括
#定义MAXBUF 50
结构节点
{
字符数据[MAXBUF];
结构节点*下一步;
};
内部主(空)
{
文件*f;
f=fopen(“text.txt”,“r”);
如果(f==NULL)退出(“错误”\n);
结构节点*root=NULL;
结构节点*指针=NULL;
root=malloc(sizeof(struct node));
指针=根;
char-buf[MAXBUF];
while(fgets(buf,MAXBUF,f)!=NULL)
{
strncpy(指针->数据,buf,MAXBUF);
指针->下一步=malloc(sizeof(struct node));
指针->下一步=空;
指针=指针->下一步;
}
fclose(f);
}
因此,下次循环时:

while(fgets(buf, MAXBUF, f) != NULL)
    {
        strncpy(pointer->data, buf, MAXBUF);
指针->数据将为空。您可能希望在strncpy之前测试指针是否为NULL,并在那里创建一个malloc节点

请注意,您似乎也从未释放这些节点中的任何一个

while(fgets(buf, MAXBUF, f) != NULL)
    {
        strncpy(pointer->data, buf, MAXBUF);