c - Segmentation fault with linked list when i assign a value
问题描述
#include<stdio.h>
#include<stdlib.h>
typedef struct node {
int data;
struct node * next ;
}Node ;
typedef Node * List ;
int main(void){
List *l;
int a = 2;
int b =12;
l = malloc(sizeof(Node));
(*l) -> data = a;
printf("%d\n", (*l)->data);
(*l) = (*l)->next;
l = malloc(sizeof(Node));
(*l) -> data = b;
printf("%d\n", (*l) ->data);
(*l) = (*l)->next;
(*l) = NULL;
}
Hi guys!
I am writing a simple code with linked list, my goal is to write into the list 2 values a
and b
. The problem is that the application goes in segmentation fault probably in this line (*l) -> data = a;
.
I know there are a lot of topic similar to this, but anyway I cannot fix my problem.
解决方案
After this
l = malloc(sizeof(Node));
Pointer l
received the address for something of Node
size.
This dereferences the pointer twice, i.e. it uses the pointed-to content as a pointer, dereferences it and access who-knows-where, which triggers the segfault (if you are lucky).
(*l) -> data = a;
Once is sufficient:
l -> data = a;
or
(*l).data = a;
This would fix the segfault.
However, l
is declared as pointer-to-(typedefhidden-pointer-to-Node).
That declaration matches dereferencing twice.
To clean that up, I propose to declare l
as nonhidden pointer to Node
.
Node *l;
As far as I can tell, that should be appropriate for the codes purpose.
Or declare as hidden pointer to Node
, i.e. as List
.
List l;
Maybe you actually need a double pointer for unmentioned requirements.
But in that case please make a separate question, with code which demonstrates that need. It will take more explanation about two levels of mallocing, matching the two levels of pointer.
After fixing the segfault described in this question, your code will have foreseeable problems, based on faulty handling of linked lists. Please also make a separate question on those problems, they are unrelated to the pointer-type nesting depth mismatches discussed here.
推荐阅读
- php - 为什么添加此脚本时 POST 方法不起作用?
- django - 返回 django 查询集中的第一个对象
- amazon-web-services - AWS DataSync 可以更新修改的文件吗?
- python - 在命令行应用程序中存储消费者密钥的安全方法是什么?
- rust - type Item = &i32 ---> 如何使用 Item 将类型取消引用到 i32?
- python - 将函数参数动态传递给另一个函数
- javascript - 如何使工具提示立即出现?
- ios - 在另一个视图中插入按钮时,尽管没有将 .tabitem 调用到标签栏,SwiftUI 仍会继续添加额外的按钮
- python - 无法连接到 unix:///var/run/docker.sock 上的 Docker 守护程序。docker 守护进程正在运行?
- python - 根据大型 Pandas 数据框中的条件链接行对