简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM