链接列表无休止地循环

fbo*_*tti 1 c

为了学习,我正在编写一个简单的链表实现.我的链表由node包含int值和指向下一个节点的指针的结构组成.当我运行我的代码时,它会无休止地循环,即使它应该在到达NULL指针时终止.我究竟做错了什么?

#include <stdio.h>

struct node {
  int value;
  struct node *next_node;
};

struct node * add_node(struct node *parent, int value)
{
  struct node child;
  child.value = value;
  child.next_node = NULL;

  parent->next_node = &child;
  return parent->next_node;
}

void print_all(struct node *root)
{
  struct node *current = root;

  while (current != NULL) {
    printf("%d\n", current->value);
    sleep(1);
    current = current->next_node;
  }
}


int main()
{
  struct node root;
  root.value = 3;

  struct node *one;
  one = add_node(&root, 5);
  print_all(&root);
}
Run Code Online (Sandbox Code Playgroud)

das*_*ght 5

您的程序显示未定义的行为:您正在设置指向本地分配的指针struct:

struct node child;
child.value = value;
child.next_node = NULL;

parent->next_node = &child;
return parent->next_node;
Run Code Online (Sandbox Code Playgroud)

由于child是在堆栈上,返回指向它的父级会导致未定义的行为.

您需要child动态分配才能使其工作:

struct node *pchild = malloc(sizeof(struct node));
// In production code you check malloc result here...
pchild->value = value;
pchild->next_node = NULL;

parent->next_node = pchild;
return parent->next_node;
Run Code Online (Sandbox Code Playgroud)

现在您已经动态分配了内存,不要忘记调用free链表中每个动态分配的节点以防止内存泄漏.