c-创建新的循环链表时出现分段错误



我正在尝试实现一个循环的互连列表。但是,当我尝试运行程序时,会收到一条Segmentation fault (core dumped)消息。

我有一个简单的list.h文件,在其中我定义了所有的structsfunctions

/**
* @brief  defines a cyclical interlinked list
*/
typedef struct node {
int          number;  // save a number for learning purpose
struct node *next;    // pointer to the next node in the list
} node_t;
/**
* @brief  defines a variable for the cyclical interlinked list
*         -> this is the only known element
*/
static node_t *person_list;

/**
* @brief Constructor
*/
void list_new();

然后我在list.c文件中实现了这一点。

#include <stdio.h>
#include <stdlib.h>
#include "list.h"
void list_new() {
node_t *pointer = malloc(sizeof(node_t));

if (pointer == NULL) {
fprintf(stderr, "ERROR: failed to allocate a new list");
exit(EXIT_FAILURE);
}

person_list->next = pointer;

if (person_list == person_list->next) {
printf("It works.");
}   
}

然而,我的呼叫list_new()似乎不起作用。

#include "list.h"
int main(int argc, char* argv[])
{
list_new();
return EXIT_SUCCESS;
}

我知道CCD_;不属于你";。但我不知道我在哪里试图访问不属于我的内存。

我的假设是,我对静态变量person_list做了一些错误的事情,但我不知道是什么。

你能告诉我我做错了什么吗?

您取消引用了person_list,但没有为其分配有效指针。

修复示例:

#include <stdlib.h>
#include "list.h"
int main(int argc, char* argv[])
{
person_list = malloc(sizeof(*person_list)); /* allocate and assign valid pointer */
if (person_list == NULL) return 1; /* check if allocation is successful */
list_new();
return EXIT_SUCCESS;
}

最新更新