Script crash with array of engine objects after wait(1)

Posted By: CanadianDavid

Script crash with array of engine objects after wait(1) - 06/24/14 21:31

Can anyone explain why the following simple program crashes after the TEXT* objects' first strings are printed for the first time?

Code:
#include <acknex.h>
#include <default.c>

TEXT** makeTexts() {
	TEXT* array[2];
	array[0] = txt_create(10, 1);
	array[1] = txt_create(10, 1);
	
	int i;
	for(i=0; i<10; i++){
		str_cpy((array[0].pstring)[i], "Text1");
		str_cpy((array[1].pstring)[i], "Text2");
	}
	
	return array;
}

function printMessages(TEXT** array){
	printf("%s", _chr((array[0].pstring)[0]));
	printf("%s", _chr((array[1].pstring)[0]));
}

function main() {
	TEXT** array = makeTexts();
	while(1){
		printMessages(array);
		wait(1);
	}
}



The code works fine when it is outside the while loop; the code works until a wait(1) is encountered.
Posted By: txesmi

Re: Script crash with array of engine objects after wait(1) - 06/24/14 21:45

Hi,
There is no problem with the engine objects. The array is a local variable only valid while the function is used. You need to allocate the array to be able to use it out of the function.

Code:
TEXT **array = sys_malloc ( sizeof(TEXT*) * 2 );

Posted By: CanadianDavid

Re: Script crash with array of engine objects after wait(1) - 06/24/14 22:16

Great thanks for the clarification!
Posted By: txesmi

Re: Script crash with array of engine objects after wait(1) - 06/24/14 22:38

glad to help grin

don't forget to remove all the created stuff at the end.

Code:
void removeTexts ( TEXT **array )
{
   int i = 0, ii = 0;
   for ( i=0; i<2; i+=1 )
   {
      for ( ii=0; ii<array[i].strings; ii+=1 )
         str_remove ( (array[i].pstring)[ii] );
      ptr_remove ( array[i] );
   }
   sys_free ( array );
}

Posted By: CanadianDavid

Re: Script crash with array of engine objects after wait(1) - 06/24/14 22:45

You're right I almost forgot! Thanks again for your help!
© 2024 lite-C Forums