title: Why does my program crashes when I tried adding a node inside a function but works in the main function
body: <p>I tried allocating a new node for a linked list using:</p>
  
  <pre><code>struct node *n;
  n=(struct node*)malloc(sizeof(struct node));
  </code></pre>
  
  <p>When I try to do this inside a function which I call <code>newnode()</code>, it crashes. However, when it works when it is done inside the <code>main()</code> function.My full code is as follows:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  #include &lt;stdbool.h&gt;
  
  struct node{
  int item;
  struct node *next;
  };
  
  struct linkedlist{
      int size;
      struct node *head;
  };
  
  void split(struct linkedlist *LL,struct linkedlist *L_odd,
  struct linkedlist *L_even);
  
  void printlist(struct linkedlist *LL);
  
  void generate();
  
  void newnode(int i,struct linkedlist *LL);
  
  int main(){
      struct linkedlist *L=(struct linkedlist*)malloc(sizeof(struct linkedlist));
      L-&gt;head-&gt;item=1;
      newnode(2,L);
      newnode(3,L);
      printlist(L);
   return 0;
  }
  
  void split(struct linkedlist *LL,struct linkedlist *L_odd,
  struct linkedlist *L_even){
      bool odd=1;
      bool start=1;
      struct node *temp=malloc(sizeof(struct node));
      struct node *tempo=L_odd-&gt;head;
      struct node *tempe=L_even-&gt;head;
      temp=LL-&gt;head;
      while (temp-&gt;next != NULL){
          if(odd==1){
              if (start == 1 ){
                  start=0;
              }
              else{
              tempe-&gt;next=temp-&gt;next;
              tempe=tempo-&gt;next;
              }
              tempo-&gt;item=temp-&gt;item;
              odd=0;
          }
          else if(odd==0){
              tempo-&gt;next=temp-&gt;next;
              tempo=tempo-&gt;next;
              L_even-&gt;head-&gt;item=temp-&gt;item;
              odd=1;
          }
          temp=temp-&gt;next;
      }
  }
  
  void printlist(struct linkedlist *LL){
      struct node *temp=LL-&gt;head;
      do{
          printf("%d ",temp-&gt;item);
          temp=temp-&gt;next;
      }while(temp!= NULL);
  }
  
  void generate(){
  
  }
  
  void newnode(int i,struct linkedlist *LL){
      struct node *n;
      n=(struct node*)malloc(sizeof(struct node)); //Program crashes here
          printf("%d",LL-&gt;head-&gt;item);
      //n-&gt;item=i;
      struct node *temp=LL-&gt;head;
  
      while (temp-&gt;next!=NULL){
          temp=temp-&gt;next;
      }
      //temp-&gt;next=n;
      //n-&gt;next=NULL;
  }
  </code></pre>
  
  <p>Why is this so?</p>