c - 创建新的循环链接列表时出现分段错误
问题描述
我正在尝试实现一个循环链接列表。Segmentation fault (core dumped)
但是,当我尝试运行我的程序时会收到一条消息。
我有一个简单的list.h
文件,我在其中定义了所有我的structs
和functions
.
/**
* @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;
}
我知道 asegmentation fault
是尝试访问“不属于您”的内存时导致的特定错误。但我不知道我在哪里尝试访问不属于我的内存。
我的假设是,我对静态变量做错了,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;
}
推荐阅读
- java - Java初学者租赁计划
- xml - XML 模式:“ref”或“name”必须出现在本地元素声明中
- php - 引用、指针和标识符有什么区别?
- javascript - 不和谐的私人消息命令
- c# - Unity UDPClient 未在 android 构建上接收广播。编辑工作。定位电话 IP 有效
- solr - 如何使用 Morphlines conf 文件读取 DECIMAL(38,10)
- angular - 如何在 Angular 6 中测试模板驱动的表单
- javascript - 动态更改输入值(javascript)
- ios - 在 Twilio 聊天 iOS APN 推送负载中将 mutable-content 设置为 1
- javascript - 在 WKWebView iOS 中加载本地 React 应用程序