Odd memory behaviour with xmem2root

I have used the code from ximport.c to make a function that takes a file in xmem and returns a string. This works fine when the file is small but when the file gets a little bigger is seems to have some memory leak, and it ovewrites the HttpState->substate variable. Does anyone have any idea what I am doing wrong?

Relavent bit of code:

char buffer[5001];

printf("fileId = %d
", fileId);
switch(fileId) {
case 1:
file = ana_1;
break;

case 2:
	file = ana_2;
	break;

}
printf("physical address1: %06lx
",(long)file);
retStr = xmem2root(&length,file,sizeof(long));
if(length>(5000)) // restrict to array length
length=(5000);
printf("length = |%ld|
", length);
printf("substate %d s = %d
", 1, state->substate);
retStr = xmem2root(buffer,file+4,(int)length);
printf("substate %d s = %d
", 2, state->substate);

And its output:

fileId = 1
physical address1: 019553
length = |721|
substate 1 s = 2
substate 2 s = 2

fileId = 2
physical address1: 019828
length = |909|
substate 1 s = 3
substate 2 s = 26475

Note the array is more than big enough for the data.
I am using Dynamic C 10.40 running on a RCM 4000 attached to the development board.