Question

I am new to data structures. I have written a fairly simple program to search for an integer in a link list. Function is suppose to return pointer to relevant position, but when called in main() it is returning null(or just garbage may be). (printf messages are inserted for diagnostics.)

Link list :

struct list
{
        int data;
        struct list * link;
};

Search function :

struct list * search_list(struct list * head_ptr, int x)
{
        printf("\nfunc search head addr : 0X%x ",head_ptr);
        if(head_ptr==NULL)
        {
                printf("Null found.\n");
                return NULL;
        }

        else if (head_ptr->data == x)
        {
                printf("element found returing : 0X%x ",head_ptr);
                return head_ptr;
        }
        else
        {
                printf("not found , next");
                search_list(head_ptr->link,x);
        }

}

Call inside main () :

tmp_list_ptr = list_head_ptr;
tmp_list_ptr = search_list(list_head_ptr,15);
if(tmp_list_ptr == NULL)
        printf("main : Not found : 0X%x\n",tmp_list_ptr);
else
        printf("main : found at : 0X%x\n",tmp_list_ptr);

return 0;

Program Output :

[0X1dd33250 : 19,]
[0X1dd33230 : 18,]
[0X1dd33210 : 17,]
[0X1dd331f0 : 16,]
[0X1dd331d0 : 15,]
[0X1dd331b0 : 14,]
[0X1dd33190 : 13,]
[0X1dd33170 : 12,]
[0X1dd33150 : 11,]
[0X1dd33130 : 1,]
[0X1dd33110 : 2,]
[0X1dd330f0 : 3,]
[0X1dd330d0 : 4,]
[0X1dd330b0 : 5,]
[0X1dd33090 : 6,]
[0X1dd33070 : 7,]
[0X1dd33050 : 8,]
[0X1dd33030 : 9,]
[0X1dd33010 : 10,]
Searching for 15. 
func search head addr : 0X1dd33250 not found , next
func search head addr : 0X1dd33230 not found , next
func search head addr : 0X1dd33210 not found , next
func search head addr : 0X1dd331f0 not found , next
func search head addr : 0X1dd331d0 element found returing : 0X1dd331d0 main : Not found : 0X0

Why it is returning NULL to main ? Could you help me please? Note : Example taken from : The Algorithm Design Manual, Steven S. Skiena, 2nd edition https://i.stack.imgur.com/uhEZC.png

Was it helpful?

Solution

Your recursive call of search_list() should actually return the result. Instead, your function is calling search_list() recursively and then implicitly throwing away its return value.

This should have generated a compiler warning, such as "control reaches end of non-void function."

Depending on your computer's architecture, you may end up with garbage results. This is what we refer to as "undefined behavior"! For example, on a 32-bit Intel processor, the return value of a function is stored in the eax register. Depending on how the compiler decided your program would use the processor's registers, your function may have returned the result of some other computation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top