#Is this function "safe" for a microcontroller?

10 messages · Page 1 of 1 (latest)

storm locust
#
typedef struct
{
    char cmd[4];
    unsigned char values[10];
    unsigned char numValues;
} parsedCommand;

parsedCommand parseCommand(unsigned char* input)
{
    parsedCommand data;
    data.numValues = 0;
    const char* delimiter = " ";
    char* token = strtok(input, delimiter);
    strncpy(data.cmd, token, sizeof(data.cmd) - 1);
    data.cmd[sizeof(data.cmd) - 1] = '\0';

    while (token != NULL && data.numValues < sizeof(data.values))
    {
        token = strtok(NULL, delimiter);
        if (token != NULL)
        {
            data.values[data.numValues] = atoi(token);
            data.numValues++;
        }
    }

    return data;
}

My input is guaranteed to be null terminated. It is basically the buffer in RAM for a string of characters received over UART. I have an already established function that takes each character and appends to my buffer (input in the context of the function above). After the data is received, it finishes by appending '\0' to the buffer in RAM.

rapid badge
#

There is just one thing here - you don't check for validity of the input

#

So, if you actually got the command size you expected

#

And didn't check if parsing of the int succeeded

#
  • you don't check for potential overflow, if int returned from atoi actually fits in uchar
#

Also, I think you can simplify the while loop slightly:

while ((token = strtok(...)) != NULL && data.numValues < sizeof(...)) {
   values[...] = Atoi(...);
   Numvalues++;
}
storm locust
#

thanks

#

i fixed those issues

loud minnow
#

most C is safe in microcontrollers. maybe assert on var sizes.. malloc/free/new/delete are the killers in microcontrollers.

#

strtok() might be larger than you need. i'd imagine a custom tokenizer just for ' ' delimiting is less code