Performance Issue probably run out of Ram

I can help you with the parameter/variable 'length'. Make it and everything that does math with it into 32-bit type long that can hold +/- 2 billion. You can mix int in there if you cast to long.

int N = 1000; // N is a 16-bit value
long X = 1000000; // X is a 32-bit value
long Y = X - (long) N; // they (long) before N forces the compiler to use a 32-bit value for the math

Making sure the compiler does what you have in mind can sometimes make the difference. Besides some extra typing it doesn't hurt the code a bit and bonus is it is more clear to read. Same goes with parenthesis, extras don't hurt.

If it was me and I wanted my code debugged sooner, I'd salt in some serial prints to see what's going on with the variables and try changing that function definition to use pointers.

int myArray[ 40 ];
(int *) myArrayPtr = myArray; // points to myArray, the parenthesis is for clarity only
int my2dArray[ 8 ][ 8 ];
(int **) my2dArrayPtr = my2dArray; // pointer to pointer to array
my2dArray = &(my2dArray[ 4 ]); // the pointer doesn't have to point to the start of the array

That's just a bit of using pointers, a very powerful part of C. You can have pointers to functions and objects too. There is pointer math, myArrayPtr++ points to the next element in myArray for instance. The subject of pointers is good fundamental reading and practice in C/C++.

void myFunction( int *AP, long arg1 ) { .... }; // makes sure that only a pointer is passed

However it is up to you that the pointer accesses valid data space, what I do is make the array global to avoid scope problems.