String-based linked list in C produces segmentation fault -
---------- #include <stdio.h> #include <stdlib.h> #include <string.h> struct node { char *val; struct node *next; }; void add_to_list(struct node **, char *); void list_all_elements(struct node *); int main (int argc, char **argv) { char *val; struct node *head = null; { scanf("%s",val); add_to_list(&head, val); } while(val[0] != '\\'); list_all_elements(head); } void add_to_list(struct node **head, char *val) { //this produces segfault struct node *temp = malloc(sizeof *temp); //edit - fixed per comments temp->val = malloc(strlen(val) + 1); strcpy(temp->val, val); temp->next = null; if(head!=null) temp->next = *head; *head = temp; } void list_all_elements(struct node *head) { while(head!=null) { printf("%s\n",head->val); head = head->next; } }
so compiled implement linked list. now, reason malloc'ing produces segmentation fault.
to sure, replaced char * char [] , code runs fine. malloc faulting due or there trivial error can't seem find?
you did not allocate memory pointed variable val
, going read string.
char *val; //... { scanf("%s",val); add_to_list(&head, val); }
variable val not initialized programme has undefined behaviour.
and function add_to_list
invalid. illustration sizeof(val)
has same value equal size of pointer char. not yield size of string pointed pointer. instead of operator sizeof
shall utilize function strlen
the function written like
void add_to_list( struct node **head, const char *val ) { struct node *temp = malloc( sizeof *temp ); size_t n = strlen( val ); temp->val = malloc( n + 1 ); strcpy( temp->val, val ); temp->next = *head; *head = temp; }
c string pointers linked-list
No comments:
Post a Comment