Sorted linked list function (C)
<p>I'm a beginner who has been self-teaching for the past weeks data structures. I'm trying to create a function that inserts an integer into a linked lists in a sorted fashion.</p>

<p>Here's my function:</p>

<pre><code>void sortedInsert(int n)
{
    node *temp = malloc(sizeof(node));
    temp-&gt;data= n;

    //if list is empty or n is less than minimum number in the list, insert at the beggining.
    if(head == NULL || n &lt; head-&gt;data )
    {
        temp-&gt;next = head;
        head = temp;
    }
    else
    {
        node *cur, *prev, *temp;
        for (cur = head, prev = NULL
             cur != NULL &amp;&amp; cur-&gt;data &lt; n;  //if n is less than cur-&gt;value it breaks out of loop
             prev = cur, cur = cur-&gt;next);

         //now cur is pointing at last node or the node it broke out off

         if( n &lt; cur-&gt;data)
         {
             temp-&gt;next = cur;
             prev-&gt;next = temp;
         }
         else
         {
             //if its larger than the maximun number in the list
             //insert at end 
             temp-&gt;next = NULL;
             cur-&gt;next = temp;
         }

         free(cur);
         free(prev);
    }
}
</code></pre>

<p>Output:</p>

<pre><code>How many numbers?
4
Enter the number
10
List is:  10
Enter the number
4
List is:  4 10
Enter the number
5

Process returned -1073741819 (0xC0000005)   execution time : 7.161 s
Press any key to continue.
</code></pre>

<p>It crashes out whenever I insert a number greater than those on the list.
I'll appreciate any help or guidance I could get.</p>