[Expat-discuss] Bug in my code or bug in Expat?

Jean-Claude Gervais jc.gervais@videotron.ca
Tue, 24 Sep 2002 12:49:18 -0400


Hi,

	I'm trying to write code to read an XML file, but my application keeps
crashing and I can't figure out what the problem is.

	During the StartElementHandler function, I am simply trying to trace what
the names and values of the elements are and the program crashes.

	Could you PLEASE look at the OnStartElementHandler function, and tell me if
I'm doing something wrong?


PS - The code DOES work, most of the time and prints out a series of
informations, it chokes if the file is large, but I can't see why it would
make any difference.

------------------------------------

#include <expat.h>



void OnStartElementHandler( void * userData, const XML_Char * name, const
XML_Char ** atts ) {

	for ( unsigned uDepth = 0;; uDepth++ ) {

		if ( NULL == *atts ) {

			break;

		}

		const XML_Char * pszAttribute	=	*atts;
							atts++;	/* Increment to next item, the VALUE. */
		const XML_Char * pszValue	=	*atts;

		TCHAR	szLogMessage[1024];

		sprintf( szLogMessage, "%s=\"%s\"", pszAttribute, pszValue );
		wxLogDebug( szLogMessage );

	}

}


void OnCharacterDataHandler( void * userData, const XML_Char * s, int len )
{

	LPTSTR	lpszLogMessage;

	lpszLogMessage = (LPTSTR)calloc( sizeof( TCHAR ), len + 1 );

	if ( NULL == lpszLogMessage ) {

		assert( FALSE );
		return;

	}

	strncpy( lpszLogMessage, s, len );

	wxLogDebug( lpszLogMessage );

	free( lpszLogMessage );

}


void OnEndElementHandler( void * userData, const XML_Char * name ) {

	wxLogDebug( name );

}


class XML_PARSER_INFO {

    public:

        XML_Parser	m_parser;

};
typedef XML_PARSER_INFO * PXML_PARSER_INFO;
typedef XML_PARSER_INFO FAR * LPXML_PARSER_INFO;


#define	READ_XML_BUFFER_SIZE	( 1024 * 4 )	/* 4K of parsing fury! */


int test( LPCTSTR lpszXMLFile ) {

	XML_PARSER_INFO	Info;

	Info.m_parser = XML_ParserCreate( "ISO-8859-1" );

	XML_SetUserData( Info.m_parser, &Info );
	XML_SetElementHandler( Info.m_parser, OnStartElementHandler,
OnEndElementHandler );
	XML_SetCharacterDataHandler( Info.m_parser, OnCharacterDataHandler );

	FILE * pFile = fopen( lpszXMLFile, "rb" );

	if ( NULL == pFile ) {

		return -1;

	}

	int		iResult		= 0;
	int		iTotalCount	= 0;
	size_t	uRead		= 0;

	TCHAR	cBuffer[READ_XML_BUFFER_SIZE];

	while( ! feof( pFile ) ) {

		uRead = fread( cBuffer, 1, READ_XML_BUFFER_SIZE, pFile );

		if ( 0 >= uRead ) {

			assert( FALSE );
			break;

		}

		iTotalCount += uRead;

		TCHAR szMessage[128];
		sprintf( szMessage, "At offset %d", iTotalCount );
		wxLogDebug( szMessage );

		iResult = XML_Parse( Info.m_parser, cBuffer, uRead, 0 != feof( pFile ) );

//		assert( iResult == 0 );


	}

	fclose( pFile );

	XML_ParserFree( Info.m_parser );

	return iResult;

}