Reason for segmentation fault despite using equivalent statements

  • A+

I wrote a function for implementing merge sort on singly linked list, where every element has an integer and a next pointer. One of the function splitlist is used to split the given linked list into two linked lists

void splitList(struct node* source, struct node** frontRef, struct node** backRef) {     struct node *s, *f;     s = source;     f = s->next;     while(f && f->next)     {         s = s->next;         f = f->next->next;     }     *frontRef = source;     f = s->next;     s->next = NULL;     *backRef = f; } 

Here source is a pointer to given linked list and frontRef and backRef are references to pointer which need to be assigned through this function. fronRef should refer to first linked list and backreef should refer to second one. This code gives segmentation fault when the lines

*frontRef = source; *backRef = f;

are replaced by

frontRef = &source; backRef = &f;

I fail to understand the reason for this as both set of statements are equivalent to each other


as both set of statements are equivalent to each other

They absolutely aren't.

  1. *frontRef = source means dereference frontRef and invoke operator= on the returned lvalue expression of type node.

  2. frontRef = &source means take the address of source and assign it to frontRef.

If frontRef is uninitialized or null, (1) is undefined behavior, but (2) is fine.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: