PRB: Program Example DMTEST.CPP Gives Incorrect Output

ID Number: Q84735

1.00

MS-DOS

docerr

Summary:

SYMPTOMS

The first program example given in the Microsoft Foundation Class

(MFC) tutorial, DMTEST.CPP, gives incorrect output. The output

shown in the tutorial is correct.

CAUSE

The problem is within the CPersonList::FindPerson() function, shown

on page 72 of the "Class Libraries User's Guide" and located in

PERSON.CPP. The DMTEST program is testing a data model developed in

the second chapter of the MFC tutorial. The problem occurs when the

CPersonList::FindPerson() function checks the list for a person who

is not in it. In this example, "Banipuli" would not be in the list.

The TestFindPerson function, shown on page 78 and located in

DMTEST.CPP, makes a call to CPersonList::FindPerson(), passing

"Banipuli" as the parameter. The following fragment shows that

TestFindPerson would expect CPersonList::FindPerson to return an

empty list:

// TestFindPerson - test CPersonList::FindPerson

.

.

.

CPersonList *pFound = pDataBase->FindPerson( "Banipuli" )

if( pFound->IsEmpty() )

{

printf( " No matching persons\n" );

}

else

{

printf( " Found matching persons\n" );

#ifdef _DEBUG

pFound->Dump( afxDump );

#endif

}

.

.

However, the following code shows that CPersonList::FindPerson()

will return a null pointer if the person is not in the list:

if ( pNewList -> IsEmpty() )

{

delete pNewList;

pNewList = NULL;

}

return pNewList;

So the code fragment from TestFindPerson() will call IsEmpty on a

NULL pointer. The value returned from the call is FALSE; therefore,

the message "Found Matching Persons" is the incorrect program

output.

RESOLUTION

To correct this problem, change if( pFound->IsEmpty() ) to

if( pFound == NULL ), so that the code fragment from TestFindPerson

shown above resembles the following:

pFound = pDataBase->FindPerson( "Banipuli" )

if( pFound == NULL )

{

printf( " No matching persons\n" );

}

else

{

printf( " Found matching persons\n" );

#ifdef _DEBUG

pFound->Dump( afxDump );

#endif

}

Additional reference words: S_C AFX