Vex Pros Fget crashes cortex


char *a = "";

void InitUart()
{
	usartInit(uart1, 115200, SERIAL_8N1);
}

void GetUartStr()
{
	a = (char *)malloc(sizeof(char) * 120);

	if( fcount(uart1) > 30 )
	{
		fgets( a, 30, uart1);
		printf("Uart \n%s\n\r", a);

	}
}

I have an Arduino connected to the cortex via Uart @ baud of 115200 and it is sending out a string 5 times a second the cortex is suppose to grab this string and parse it but it crashing every 10 seconds

Can anyone help with this?

Hi @robokiller,

My initial reaction is that every time GetUartStr is called, new memory is allocated for the string. If you call this function enough times (15 times with a minimal amount of other memory to be precise), eventually malloc will return a NULL pointer when there is no more memory available. You then try to write to a NULL pointer (


fgets

), which causes a SEGFAULT and resets the microcontroller. Try something like this:


char* a;

void InitUart() {
    usartInit(uart1, 115200, SERIAL_8N1);
    a = (char*)malloc(sizeof(char) * 31); 
}

void GetUartStr() {
    if(fcount(uart1) > 30) {
        fgets(a, 30, uart1);
        printf("Uart \n%s\n\r", a);
    }
}

You were right, Thank you.

Btw should InitUart(); be in initialize() or initializeIO()?

As per the documentation,

So it may be called in initializeIO() or after. Calling it in


initializeIO

or


initialize

is up to you