0

I am decoding a string field with NanoPB. During the decoding, the string returns to me with the correct content, however, there are some left-over characters at the end.

My proto message:

syntax = "proto2";

message stringCallback{
    required string name = 1;
    required string surname = 2;
    required int32 age = 3;
}

My decode function:

bool stringCallback_decode(pb_istream_t *stream, const pb_field_t *field, void** arg)
{
  //Buffer to store the decoded string
  char buffer[128];
  //Check how many bytes the string will be
  Serial.println(stream->bytes_left);

  //Decode the string and store it in the buffer
  if (!pb_read(stream, (uint8_t*)buffer, stream->bytes_left))
      return false;
  
  //Copy the string into the arg to place it in its placeholder
  strcpy((char*)*arg, buffer);
  
  //Print the string (gibberish)
  Serial.println((char*)*arg);
  return true;
}

I run the code with the following input message: ␆Doesnt␒␄Work␘␗ Where the first string contains 'Doesn't' and the second 'Work' and finally the int contains 23.

The output of my decoder is the following for name:

bytes left = 6 -> output: Doesnt�?P&�? 

The output of my decoder is the following for surname:

bytes left = 4 -> output: Worknt�?P&�?

The output is message is there, and the bytes to read are also the correct length. However, how do I get rid of the gibberish at the end?

J.Meulenbeld
  • 185
  • 1
  • 17
  • 1
    When you know "bytes left" = 6, why do you expect "Doesnt\0" (7bytes long) to be loaded? – Fe2O3 Aug 23 '22 at 09:06
  • @Fe2O3 So you are saying I should add the null terminator my self. I think thats a good idea. Ill try that – J.Meulenbeld Aug 23 '22 at 09:09
  • 1
    I don't know the system, but, from the symptoms, you could `memset()` the whole 128 bytes to '\0' before fetching those 6 or 4 bytes... The null terminator will be waiting there... – Fe2O3 Aug 23 '22 at 09:11

0 Answers0