hi all,

I write this program under the C++ not C. But I heaively used the
malloc() and free() functions in my code.

In brief what my code does is just allocate memory for NFA transition
table. It grows dynamically. When the number of transitions is a %4
then it will automatically free the previously allocated memory for the
two arrays and allocate a new array with more additional 17 bytes.
4 integer and 1 - zero terminator byte (zero terminator is necessary
because it is used in by the free() call).

here is the code ,

int TransistionTable::AddTransistion ( int stateId , int nextStateId )
{
	// we are first check if adding this state will 
	// overflow our allocated memory.
	if ( (numberOfTransistions ) %4 == 0 )
	{
		// then we need to allocate some memory
		int * pNewIntId = (int *)malloc ( numberOfTransistions *4 + 17);
		int * pNewTransistion = (int *) malloc ( numberOfTransistions * 4 + 17);

		memcpy ( ( void *)pNewIntId  ,( void* ) pIntId ,numberOfTransistions*4);
		memcpy ( ( void *)pNewTransistion , ( void *) pTransistion , numberOfTransistions*4);

		// then we just release the old memory
		if ( ! numberOfTransistions == 0) 
		{
			free (( void*) pIntId);
			free (( void*) pTransistion);
		}
		// then we update the pointer values
		pIntId = pNewIntId ;
		pTransistion = pNewTransistion ;

	}

	// then add the new value
	pIntId		 [numberOfTransistions] = stateId ;
	pTransistion [ numberOfTransistions ] = nextStateId ;
	
	numberOfTransistions++;

	// just return 0 to say nothing goes wrong
	return 0;
}

This code works prefect , and I already write a unite test for this.
My Question is how should I improve performance of the memory
management algorithm , is there is a better algorithm ?

is it oky to just allocate only 4 bytes using malloc() ? Need suggestions....

please forgive me about C++ coding standards , I know some C ppl
find very difficult to read the C++ styled code.

why dont you use realloc rather than freeing and allocating?

commented: realloc good point +1

dont go for dynamic memory allocation if u really need efficiency and u know the range (approx) of the elements u r going to have.

u can declare your array as

#define MAXTRANSITION 100
int pIntId[MAXTRANSITION];
int pTransistion[MAXTRANSITION];

throw an exception when the no. of transitions exceeds MAXTRANSITION.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.