Search code examples
c++linked-listdynamic-memory-allocationtail-recursion

Linked List would core dump while searching for an element recursively that is not present in the list


#include <iostream>

using namespace std;

class Node{
public:

int data;
Node* next;

};

//Node* head1 = new Node;

void search(int num , Node* head1)
{

if( (head1 != NULL) & (head1->data == num) )
{
    cout << "Yes";
    return ;
}
else if(head1 == NULL)
{
    cout << "No";
    return ;
}
search(num , head1->next);

//return FALSE;
 }

int main() {
int max , n;
cin >> n;
Node* head = NULL;
Node* ptr;
for(int i = 0; i < n ; i++)
{
    int num;
    cin >>num;
    Node* temp = new Node;
    temp->data = num;
    temp -> next = NULL;
    if(head == NULL)
    {
        head = new Node;
        head = temp;
        ptr = new Node;
        ptr = head;
    }
    else
    {
        ptr->next = temp;
        ptr = ptr->next;
    }
    // linked list is made;
    // traversing through the linked list;

    // search for an element;
    //cout << head->data <<"\n";


}
search(6 , head);
// I have assumed 6 won't be there in the list

 }

The linked list work fine. I have been able to build the list without running into any kind of run time errors. The only problem I have is with the search method.

It will print "YES" perfectly when the element to be searched is present but runs into run time error when the element is not there instead of printing "NO";

I have used recursion(intended) to solve this problem as it is something I am not very comfortable with .

To save time you can ignore the main function as it runs fine. I have just provided that for reference or any other valuable suggestions.

Also I have checked other answers on SO and realized that most of the run time errors in Linked List is because of bad memory allocation . I have checked my code and found that memory allocation has been done properly , or so I think.


Solution

  • Your mistake is here

    if( (head1 != NULL) & (head1->data == num) )
    

    it should be

    if( (head1 != NULL) && (head1->data == num) )
    

    && does a logical and, plus if the left hand side is false the right hand side is not evaluated. & does a bitwise and, but always evaluates both sides.

    So, in your code, when head1 == NULL then head1->data still gets evaluated, resulting in a dereference of a null pointer and a crash.

    Just change & to &&.

    Nothing wrong with your recursion however.