Remote Procedure Call with String parameter sends extra characters appended

I was experimenting with the remote procedure calls on my devices and noticed that when sending strings as a parameter the device would receive that string with extra characters appended.

Here is the code on the device end and the screenshots of the error occurring:

Hi @npschwab,

I think what’s happening here is that the strings coming to you as part of a CBOR packet are not null terminated. The code you posted copies the length as reported by CBOR (no null terminator) and passes it to the function that is logging the value. This function is expecting a null terminated string so it reads until it finds it, which in this case is going past the end of the array and into uninitialized memory.

I have a couple of patterns that I use in this case. I’ve added notes to the pros/cons, but generally speaking I create an array that is the CBOR length plus one, then I sent the last member of the array to a null terminator. Then when copying the string into the array, it will have the terminator that the log function expects:

#include <stdio.h>
#include <string.h>

// Copying strings from CBOR

struct test {
  char *value;
  size_t len;
} value;

// Using memcpy
void my_memcpy_func(void) {
  char sendme[value.len + 1];
  sendme[value.len] = '\0';
  memcpy(sendme, value.value, value.len);

// Using snprintf
void my_snprintf_func(void) {
  char sendme[value.len + 1];
  // Because value.value isn't null terminated, in this case the following
  // function call depends on the array being exactly the right size
  // from devdocs: At most bufsz - 1 characters are written. The resulting
  // character string will be terminated with a null character
  snprintf(sendme, sizeof(sendme), "%s", value.value);

I tend to use snprintf a lot because it will always ensure there is a null terminator in the array. But the memcpy is likely a better option in this instance since we know the string we’re copying doesn’t have a null terminator.

Hi Mike,

Modifying the code to make the character array to be one unit greater length than the CBOR string and have a null terminator at the end resolved the issue.


Excellent, thanks for confirming the fix!