user3852803
user3852803

Reputation: 162

C linked list passing list as argument to the function

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;
}

Upvotes: 0

Views: 712

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409176

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.

Upvotes: 3

Related Questions