Search code examples
cvisual-studiopointersmallocstrcat

visual studio triggered a breakpoint when used pointer and strncat


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


Solution

  • 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';
      ...