c - Adding node to global linked list causing crash -


i'm trying add items linked list. code compiles ok when execute program, crashes before adding first node. code looks ok me must missing something.

the code uses global linked list necessary problem. think usage of may causing crash.

main.c

#include <stdio.h> #include <stdlib.h> #include "linkedlist.h"  int main (int argc, char* argv[])  {     linkedlist *canqueue;     int ii;     createlist();      file* f;     f = fopen(argv[1], "r");      if(f==null)          {         printf("error: not open file");         return 0;         }       for(ii = 0; ii < 10; ii++)         {         tincan* tempcan = malloc(sizeof(tincan));         fscanf(f, " label_%d", &tempcan->label); /*read info file label field*/         insertlast(canqueue, tempcan); /*inserts new can linked list*/         }      return 0; } 

linkedlist.h

typedef struct tincan     {     int label;     } tincan;  typedef struct node     {     tincan* data;     struct node *next;     } node;  typedef struct linkedlist     {     node *head;     } linkedlist;   void insertlast(linkedlist* list, tincan *newdata); void createlist();  extern linkedlist* canqueue; 

linkedlist.c

#include <stdio.h> #include <stdlib.h> #include "linkedlist.h"  linkedlist *canqueue;  void createlist() /*creates empty linked list*/   {     canqueue = malloc(sizeof(linkedlist));     canqueue->head = null;   }  void insertlast(linkedlist* list, tincan *newdata)     {     node* newnode = malloc(sizeof(node));     newnode->data = newdata;     newnode->next = null;      if(list->head==null)         {         list->head=newnode;         }          else             {             node* temp;             temp = list->head;             while(temp->next!=null)                 {                 temp = temp->next;                 }              temp->next = newnode;             }   printf("added end");   } 

based on response, need remove declaration main:

linkedlist *canqueue; 

it shadowing global canqueue, means later on when call insertlast:

insertlast(canqueue, tempcan); 

you operating on unintialized pointer.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -