【问题标题】:Problems creating linked list in while loop. Getting runtime error on second run in loop在 while 循环中创建链表时出现问题。在循环中第二次运行时出现运行时错误
【发布时间】:2014-09-09 18:51:15
【问题描述】:

我正在编写一个程序,将文本的每一行放在链表中的一个节点中。我想为文本中的每一行创建一个新节点。在 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);
}

【问题讨论】:

    标签: list while-loop linked-list strncpy


    【解决方案1】:
    pointer->next = NULL;
    pointer = pointer->next;
    

    因此下一次循环:

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

    pointer->data 将遵循 NULL。您可能想在 strncpy 之前测试 NULL 指针并在那里创建一个 malloc 的节点。

    请注意,您似乎也从未释放任何这些节点。

    【讨论】:

      猜你喜欢
      • 2018-09-27
      • 2016-02-14
      • 2020-07-02
      • 1970-01-01
      • 1970-01-01
      • 2014-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多