C Linked List segmentation fault 11 -


i keep getting segmentation fault: 11 error , don't know why.

my code:

typedef struct node* nodeptr; struct node {     nodeptr next;     void *val; };  struct list {     nodeptr head; }; typedef struct list* listptr;  int compare(void *one, void *two) {     if(*(int*)one < *(int*)two)         return -1;     else if(*(int*)one > *(int*)two)         return 1;      return 0; }  listptr create() {     listptr blah = malloc(sizeof(struct list));     memset(blah, 0, sizeof(struct list));      return blah; }  nodeptr scan(nodeptr head, void *obj) {     nodeptr previous, current;      previous = head;     current = head->next;      // segmentation fault here!!      while(current != null && (compare(curry->val, obj) == -1))     {         previous = current;         current = current->next;     }      return previous; }  int insert(listptr llist, void *obj) {     nodeptr newobj = malloc(sizeof(struct node));     nodeptr prevnode, nextnode;      prevnode = search(llist->head, obj);     nextnode = prevnode->next;      if((nextnode == null) || (compare(nextnode->val, obj) != 0))     {         prevnode->next = newobj;         newobj->next = nextnode;          return 1;     }     else     {         free(newobj);     }      return 0; } 

i thought head not allocated, added malloc in create blah->head, still no luck.

i think error here after debugging: current = head->next.

any appreciated! thank time!

edit: how call insert:

int main(int argc, char *argv[]) {     listptr list = create();      int x = 2;     int *p = &x;      while(*p != 0)     {         printf("\nenter number: ");         scanf("%d", p);          if(*p != 0)             insert(list, p);     }      return 0; } 

you don’t appear check whether list empty when scan it. however, without minimum complete verifiable example tells how called function, impossible tell sure did.

update

now have, seems it. create empty list , search inside insert function. search function dereferences zeroed-out pointer in head, causing segfault.

try following: first, check pointer valid in each of functions before it. empty list should fail every search. second, maximum portability, want set head pointer null (since null pointer not all-bits-zero on implementations).


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -