C - Inserting into sorted linked list with double pointers -


i'm trying create sorted linked list in c following code getting segmentation fault before of input printed. believe because i'm checking ((*link)->value < val) in while loop, @ beginning, null. tried adding conditional if there no elements in list didnt work. how check see if value add smaller without getting seg. fault?

struct nodetag {     int value;     struct nodetag *next; }; typedef struct nodetag node;  typedef struct {     node *head;     int length; } list;  void insertsorted(list *list, int val) {     node **link = &(list->head);      while (*link != null || (*link)->value < val) {         //move node correct place in list         link = &((*link)->next);     }     //create new node     node *n = (node *)malloc(sizeof(node));     n->value = val;      //set next null     n->next = null;      //insert new node     *link = n; } 

here printlist:

void printlist( list *list ) { printf( "%d elements :", list->length );  ( node *n = list->head; n; n = n->next ) printf( " %d", n->value ); printf( "\n" );  } 

input: 72 19 47 31 8 36 12 88 15 75 51 29 expected output: 8 12 15 19 29 31 36 47 51 72 75 88

here problems in code:

  • you use || instead of &&. if next member null, @ end of list, insert right there.

  • the argument name list use link in body

  • you don't need cast return value of malloc() in c , considered counterproductive, if forget include <stdlib.h>.

  • you not test allocation failure

  • you not link rest of list inserted node.

  • the function should return pointer inserted node, giving caller chance check memory allocation failure.

  • you should not comment obvious.

here corrected version:

#include <stdlib.h>  node *insertsorted(list *list, int val) {     node **link = &list->head;     while (*link != null && (*link)->value < val) {         //skip node         link = &(*link)->next;     }     //create new node     node *n = malloc(sizeof(node));     if (n != null) {         n->value = val;         n->next = *link; // link rest of list         *link = n;   //insert new node     }     return n; } 

Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -