BaloneyOs BaloneyOs - 9 days ago 5
C++ Question

Program crashing when trying to return a boolean

For this code my goal is to change some functions (more like modularize the program) so that any function that searches the database for a the memberNumber will call an actual search function which returns a boolean value.

Right now I'm already running into a problem with my program crashing whenever the searchID function returns true. When it returns false it doesn't crash.

Original working function:

bool DonorList::searchID(int memberNumber) const
{
bool found = false;
list<DonorType>::const_iterator iter = donors->begin();
while (iter != donors->end() && !found)
{
if (iter->getMembershipNo() == memberNumber)
{
found = true;
}
else
++iter;
}
return found;
}


Changed function:

bool DonorList::searchID(int memberNumber) const
{
list<DonorType>::const_iterator iter;
bool found = searchDonorLocation(memberNumber, iter);
return found;
}


Added function:

bool DonorList::searchDonorLocation(int memberNumber, list<DonorType>::const_iterator &iter) const
{
iter = donors->begin();
bool found = false;
while (iter != donors->end())
{
if (iter->getMembershipNo() == memberNumber)
{
found = true;
}
else
iter++;
}
return found;
}


I have no clue what is causing the issue other than that the program crashes whenever the newly changed function supposedly returns true. I've tried just returning searchDonorLocation(memberNumber, iter) but that causes the exact same crash.

Answer
while (iter != donors->end())
    {
        if (iter->getMembershipNo() == memberNumber)
        {
            found = true;
        }
        else
            iter++;
    }

When they match, your loop never ends because you don't bump your iterator so it can never get to the end. Is it crashing or hanging?

In your original code, you test for !found which exits the loop.

while (iter != donors->end() && !found)