1

I'm writing a simple linked list implementation for the sake of learning. My linked list consists of node structures that contain an int value and a pointer to the next node. When I run my code, it loops endlessly even though it should terminate when it reaches a NULL pointer. What am I doing wrong?

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

2 回答 2

5

您的程序表现出未定义的行为:您正在设置一个指向本地分配的指针struct

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

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

由于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;

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

于 2013-08-17T18:04:38.097 回答
4

add_node返回一个指向局部变量的指针,该变量立即超出范围,可以被其他函数重用。尝试访问它会print_all导致未定义的行为。在您的情况下,该地址似乎被current指针重用,root->next_node指向root.

要解决此问题,您应该为新节点分配内存add_node

struct node * add_node(struct node *parent, int value)
{
    struct node* child = malloc(sizeof(*child));
    if (child == NULL) {
        return NULL;
    }
    child->value = value;
    child->next_node = NULL;

    parent->next_node = child;
    return child;
}

由于这会动态分配内存,因此您需要free稍后调用。请记住不要尝试释放root,除非您将其更改为分配使用malloc

于 2013-08-17T18:04:37.550 回答