title: Adding and sorting a linked list in C
body: <p>In my assignment, I have to write a function that takes as arguments a pointer to a "LNode" structure and an integer argument. Then, I have to not only add that integer into the linked list, but also put place it so that the list is in proper ascending order. I've tried several various attempts at this, and this is my code as of posting.</p>
  
  <pre><code>LNode*  AddItem(LNode  *headPtr, int  newItem)
  {
      auto    LNode   *ptr = headPtr;
  
      ptr = malloc(sizeof(LNode));
  
      if (headPtr == NULL)
      {
          ptr-&gt;value = newItem;
          ptr-&gt;next = headPtr;
          return ptr;
      }
      else
      {
  
          while (headPtr-&gt;value &gt; newItem || ptr-&gt;next != NULL)
          {
              printf("While\n"); // This is simply to let me know how many times the loop runs
              headPtr = headPtr-&gt;next;
          }
          ptr-&gt;value = newItem;
          ptr-&gt;next = headPtr;
          return ptr;
      }
  
  }  // end of "AddItem"
  </code></pre>
  
  <p>When I run it, and try to insert say a 5 and then a 3, the 5 gets inserted, but then the while loop runs once and I get a segmentation fault.</p>
  
  <p>Also I cannot change the arguments as it's part of a skeletal code for this project. Thanks to anyone who can help.</p>
  
  <p>If it helps this is what the structure looks like</p>
  
  <pre><code>typedef struct  LNode
  {
      int                 value;
      struct  LNode      *next;
  
  } LNode;
  </code></pre>