首页 > 解决方案 > 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.

标签: clinked-list

解决方案


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.


推荐阅读