user3288091
user3288091

Reputation: 57

Segfault on returning pointer

I'm searching through a vector of Contact objects (though the type of object shouldn't affect anything) and returning a pointer to the object if its found, or null otherwise. Below is the code:

Contact* searchByLastName(string lname) {

for (auto iter = LIST.begin(); iter != LIST.end(); ++iter) {
    Contact c = *iter; //Dereference 
    if (lname.compare(c.getLastName()) == 0) {
        return &c;
    }
}
return NULL;
}

If the method returns NULL (i.e. the Contact wasn't found in LIST), the code works fine. If the contact is in the list, the program segfaults.

I've tried using nullptr instead of NULL and returning a void pointer instead of a null pointer (and doing a static_cast back to Contact* if the result is not NULL/nullptr).

I'm not sure why its segfaulting. I know that NULL is defined as 0 in C++, but using nullptr (which should just be a pointer of type void*, right?) did not stop the segfaulting.

Upvotes: 1

Views: 1777

Answers (3)

DigitalEye
DigitalEye

Reputation: 1565

You are returning the address of a local variable, which will get destroyed once the function searchByLastName exits. You should return a pointer to what the iterator points to.

Upvotes: 1

anonymous
anonymous

Reputation: 1317

Since you are returning a pointer to Contact, return whatever that is pointed to by the iterator

return &(*iter);

instead of

return &c;

Upvotes: 3

kol
kol

Reputation: 28708

You return the address of a local variable (c).

Upvotes: 2

Related Questions