-2

I dont understand the cause of the segmentation fault here. The code is:

struct node {
    int data;
    struct node* next;
};

void add(int a,struct node *lista)
{
    struct node *p;
    p=(struct node*)malloc(sizeof(struct node*));

    p->data=a;
    p->next=NULL;

    while(lista->next!=NULL)       <--- The segmentation fault is here. 
        lista=lista->next;                    
    lista->next=p;

    return lista;

}

int main(void)
{
    struct node *list=NULL;
    list_print(list);

    list=node123();
    list_print(list);

    add(7, &list);
    list_print(list);

    return 0;
}

the add function which adds a new node to the end of the list worked perfectly like this on a friends computer and setup. I get segmentation fault. i think the problem is the lista->next expression but I don't understand why. Any ideas?

Wooble
  • 87,717
  • 12
  • 108
  • 131

5 Answers5

2

void add(int a,struct node *lista)... 2nd parameter is a struct node pointer.

struct node *list=NULL; -- list is a struct node pointer.

add(7, &list); -- &list is a struct node **; this is incorrect and likely to cause add()'s `while(lista->next!=NULL) to fail its dereference.

mah
  • 39,056
  • 9
  • 76
  • 93
1
p = (struct node*)malloc(sizeof(struct node*));

This is certainly wrong. You must not allocate memory sized as the pointer itself, but as big as the actual structure. Use

p = malloc(sizeof(struct node));

or even better

p = malloc(sizeof(*p));

And don't for the love of God cast the return value of malloc().

Also, you declare list as struct node *, and your add() function also expects a struct node * - so it's erronous to pass its address to the function. Instead of

add(7, &list);

write

add(7, list);
Community
  • 1
  • 1
0

1 - you have to check if lista is not null before writhin lista->next

2 - There is an error in the malloc : p=(struct node*)malloc(sizeof(struct node));

the size to allocate is the size of a node, you allocated the size of a pointer struct node*.

3 - add(7 , lista) not add(7 , &lista) because lista is already a pointer.

Hicham
  • 983
  • 6
  • 17
0

You're passing the address of list, but the funciton takes only a pointer, in order to pass 'list' by reference, You've got to chagne the decliration of add to:

void add(int a,struct node **lista);

and then use (*lista) instead of just 'list' . ex: (*lista)->next ...

Taher
  • 11,902
  • 2
  • 28
  • 44
0

You declared 'add' to not return any type of data (void). but you're returning 'list'. either make the function work on a pointer to a pointer to 'list' (taking **list as a parameter instead of *list). or make it return a list type: struct list* add(

Taher
  • 11,902
  • 2
  • 28
  • 44