0

I'm new with linked lists and I have a bug that I cannot find. I have single linked list filled with numbers which I send as argument to the function search_tnode. If function found the number that I'm searching for it returns and in main I can use new list starting with that number. If function does not find the number it returns and in main I have empty list while I want to have original list that I sent as argument. How can I achieve this?

main:

my_list = search_tnode(my_list,key);

function:

struct t_node * search_tnode(struct t_node *start_time, unsigned long num){

    struct t_node *p;
    p = start_time;

    while(p != NULL){

        if(p->key == num){
            return p;
        }
        p = p->next;

    }

    printf("Number not found %ld \n",num);
    return start_time;
}
0

1 Answer 1

3

If you call the function and it finds a node in the list, you return that node which you assign to the list head, thereby loosing everything before that node. Loosing nodes like that will most likely introduce memory leaks in your program.

I suggest two changes to fix this: First assign to some other variable, secondly if no node was found return NULL (it's customary), and check for that.

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

7 Comments

And third: use %lu instead of %ld for unsigned longs
I want to lose all nodes before node that I'm searching for. Where in code can I free them then ? And If I don't find the number I don't want empty list or NULL, I want to continue working on the original list that I passed. I didn't understand you how can I achieve this?
@user3852803 Then assign to a temporary variable, free all the nodes from the beginning to the new head (in the temporary variable) and then assign to the head variable.
What about my question if I don't find number in the list , why I have empty list in the main?
@user3852803 Unless you do something you don't show us, you shouldn't have an empty list. Perhaps you are returning p at the end in your actual code?
|

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.