0

I can't figure out what is wrong with my insert function.

Basically in the main function I ask a user to input an integer, and it should traverse through the list RECURSIVELY and insert the number in order. Please let me know if you need anything else.

When I print out the list it only prints out 0 twice

In the main:
            **This is looped**
    printf("Enter the value you want to insert: ");
    scanf(" %d", &integer);
    current = insert(&head, integer);
    temp = current;

    while(temp)
    {
        printf("%d\n", temp->num);
        temp = temp->next;
    }


node* insert(node** head, int integer)
{
    node* temp = malloc(sizeof(node));
    node* temp1;
    node* new;

    if(*head == NULL)
    {
        temp->num = integer;
        temp->next = *head;
        *head = temp;
    }
    else if((*head)->num > integer)
    {
        temp = *head;
        temp1 = temp->next; //breaks the link
        temp->next = new;   //creates a new node
        new->num = integer;  //adds int
        new->next = temp1;   //links new node to previously broken node
        *head = temp;
    }

    else
        insert(&((*head)->next), integer);

    return(temp);
}

Thanks alot!

6
  • Where do you set the value of new? Commented Mar 18, 2013 at 11:32
  • What do you mean by that? Commented Mar 18, 2013 at 11:46
  • Is there any particular reason why you want to do this with recursion? It doesn't seem to make any sense. Commented Mar 18, 2013 at 11:53
  • @juice look at your if-statement if (*head)->num > integer... see how you use temp->next even though it has not been initialized Commented Mar 18, 2013 at 12:07
  • Thanks a lot... I caught that in my program awhile ago.. just forgot to update it here. I got it to work for 2 numbers... but then it goes in infinite loop on a 3rd number... still trying to work out why. Commented Mar 18, 2013 at 12:21

2 Answers 2

3
if(*head == NULL)
{
    (*head)->next == temp;
    temp->num = integer;
    temp->next = *head;
    *head = temp;
}

this is wrong and will cause an invalid read as *head is NULL and hence (*head)->next is invalid. It'll read from NULL + offset. Where offset depends upon the definition of your node datatype.

Sign up to request clarification or add additional context in comments.

1 Comment

But OP's got an == instead of = (which I think was the intent), so it's an invalid read which is much safer than an invalid write ;-)
1
while(temp)
{
    printf("%d\n", current->num);
    temp = temp->next;
}

I think you want to be printing out temp->num instead of current->num.

1 Comment

lol that helps... but if i enter 7 and then 3.. it still prints out 0 3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.