0

This simple code (adding element to linked list and printing it) works fine

#include <stdio.h>
struct node{
    int item;
    struct node* next;
};

void print_node (struct node* n){
    while (n!= NULL){
        printf("%d ", (*n).item);
        n = n->next;
    }
    printf("\n");
}

void append_node(struct node *list, struct node *n){

    while(list->next != NULL)
        list = list->next;

    list->next = n;

}

int main(){
    struct node n1, n2;
    n1.item = 1;
    n1.next = NULL;

    n2.item = 2;
    n2.next = NULL;

    print_node(&n1);
    print_node(&n2);

    append_node(&n1,&n2);

    print_node(&n1);

    printf("done\n");
    return 0;
}

If instead I define the append_node as following

void append_node(struct node *list, struct node n){

    while(list->next != NULL)
        list = list->next;

    list->next = &n;

}

and call it accordingly in the main (i.e., append_node(&n1, n2) ) I get a segmentation fault when running the program. And I don't understand why :)

Peter
  • 93
  • 6

1 Answers1

1

When you call append_node(struct node *list, struct node n), the argument n is copied on the function context.

When the function is leave, the context is freed, and the copy n of your data is lost.

You could use your function append_node(struct node *list, struct node n) if you make a copy of n (using malloc) before putting it in linked list.

EDIT

This may help you: What's the difference between passing by reference vs. passing by value?

Community
  • 1
  • 1
Mathieu
  • 8,840
  • 7
  • 32
  • 45
  • the content of n inside the function is erased from memory even though it has been linked to list? – Peter Feb 19 '16 at 09:21
  • 1
    Yes: in your linked list, you just put the address of `n`, which is local to the function. You may run add some `printf("address of n is %p\n", &n);` to visualise that. In that case you may notice that addresses generated by malloc and stack addresses are different. – Mathieu Feb 19 '16 at 09:26
  • All the function variables(arguments) are stored on stack and when function returns all its variables get destroyed(inaccessible, may contain some other data). – Adeel Ahmed Feb 19 '16 at 09:30
  • OK, then (just for the sake of understanding), I want to modify the function print_node so that it does not receive a pointer. I managed in writing it like this (it works): void print_node (struct node n){ while (1){ printf("%d ", n.item); if (n.next == NULL) break; n = *(n.next); } printf("\n"); } How could I write in the while something like n!=NULL, when n is not a pointer, in order to not do the break inside the loop? – Peter Feb 19 '16 at 09:35
  • @Peter: You can do so if you want. Just make sure to assign the `next` node pointers in a local `struct node* n` and using appropriate `printf` for it. – jada12276 Feb 19 '16 at 09:44