Mert Can Celik
Mert Can Celik

Reputation: 3

Getting segmentation fault while removing one element in it

This is a code that will remove one actor in a one cast. I make a connection between the movies and their cast. So this code is checking whether movie exists and then it looks its Cast and when it finds the actor that we're looking for it deletes it. HOWEVER, while this code seems so reasonable for me, I'm getting segmentation fault. What can be the reason, what we should take care in this cases not to get a segfault?

Upvotes: 0

Views: 97

Answers (2)

Florin Petriuc
Florin Petriuc

Reputation: 1176

Like DrC said, the "next" is wrong. Try this:

    void MovieDatabase:: removeActor( const string movieTitle, const string actorFirstName, const string actorLastName )
{
        for(Movie* m= headMovie; m != NULL;  m = m-> next){
               if(m-> title == movieTitle && m -> headCast !=NULL){
                        for(Cast* c = m -> headCast; c != NULL; c= c-> next){
                                if( c ->  name == actorFirstName && c -> lastName == actorLastName){
                                        Cast* temp = c-> next;
                                        delete c;
                                        c = temp;


                           }
                    }
            }
    }

}

Upvotes: 0

DrC
DrC

Reputation: 7698

At the point

if( c-> next ->  name == actorFirstName && c -> next -> lastName == actorLastName)

you are assuming c->next is not NULL yet your loop only ensures c is not NULL.

Upvotes: 1

Related Questions