简体   繁体   中英

The strcpy_s function doesn't work in my code

This function is supposed to copy a char[] into the allocated storage. For some reason the buffer is always too small for this operation.

str(char* f) {

    len = strlen(f);
    txt = (char*)malloc(len); //txt is a pointer to a char
    strcpy_s(txt, len, f);

}

For some reason the buffer is always too small for this operation.

You forgot to allocate memory for the null terminator. An empty string requires space for one character (the terminator). A string of length one requires space for two characters (1 + 1). A string of length len requires space for len + 1 characters.

That said:

  • In C, use strdup instead.
  • In C++, don't use strlen , malloc nor strcpy_s (nor strdup ). I recommend std::string .

make sure you include cstring library

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