Search code examples
segmentation-faultbinary-search-tree

searching through a BST for a certain key, getting segmentation fault when that key doesnt exist


I'm searching through a binary search tree for a node with the specified info. Here's my code:

void MovieCollection::showMovie(string movieName) {
    Movie *movie = showMovieHelper(root, movieName);
    cout << movie << endl;

    if (movie == nullptr) {
        cout << "Movie not found." << endl;
        return;
    }
    else {
        cout << "Movie:" << endl;
        cout << "==================" << endl;
        cout << "Name :" << movie->movieName << endl;
        cout << "Director :" << movie->director << endl;
        cout << "Genre :" << movie->genre << endl;
    }

    return;
}

Movie* MovieCollection::showMovieHelper(Movie *movie, string name) {
    if (  movie->movieName == name || movie == nullptr  ) {
        return movie; 
    }

    else {
        vector<string> s;
        s.push_back(name);
        s.push_back(movie->movieName);
        sort(s.begin(),s.end());

        Movie* node; 

        if (s.at(0) == name) {
            return showMovieHelper(movie->left, name);
        }
        else {
            return showMovieHelper(movie->right, name);
        }
    }
}

It works perfectly fine if I try to search for a movie that does exist in the BST, but if I send it a name that isn't in the BST, I get a segmentation fault.

What I believe should happen if the name isn't in the BST is it should eventually reach a leaf node, return left or right of that leaf node, and so return nullptr;.

Geeks for Geeks even has the same format for searching as I do [ https://www.geeksforgeeks.org/binary-search-tree-set-1-search-and-insertion/# ].

I have no clue what's going wrong with my code. I appreciate any help


Solution

  • The problem is in this expression:

    movie->movieName == name || movie == nullptr
    

    This expression is evaluated from left to right, so if move == nullptr, the left side (being evaluated first) will give undefined behaviour (probable segmentation fault). So put the second condition first:

    movie == nullptr || movie->movieName == name