0

I am implementing the JSON packetizer with the following code

int main()
{
  char* serializedMessage;
  serializedMessage = (char*)malloc(sizeof(char)* 1024);

  if (serializedMessage != NULL)
  {
    strcat(serializedMessage, "{\"");
    strncat(serializedMessage, "\":", 3);
    strncat(serializedMessage, "{", 1);
    strncat(serializedMessage, "\"ds\":[", 8);
    strncat(serializedMessage, "}", 1);
    std::cout  <<serializedMessage <<std::endl;
   }
  return 0;
}

when run in visual studio, it throws error as triggered a breakpoint. What i am missing. Any advice

Ethane Das
  • 15
  • 5
  • the integer in `strncat` should match how many chars you are appending. I am not sure, but `"\":"` aren't two chars? (you are escaping one) – fern17 Dec 15 '21 at 12:45

1 Answers1

0

You can only use strcat family of functions on targets that are C strings. serializedMessage in your code is not yet a C string, it's a chunk of uninitialized memory. How should character arrays be used as strings?

Solve this by adding a null terminator at the beginning, to form an empty string:

if (serializedMessage != NULL)
{
  serializedMessage[0] = '\0';
  ...
Lundin
  • 195,001
  • 40
  • 254
  • 396