What is the difference between strcpy and “=”? [duplicate]

白昼怎懂夜的黑 提交于 2019-12-11 08:31:02

问题


I would like to know if there is a difference between char* test = "test" and strcpy(test, "test"), and if there is one, what is this difference.

Thanks.


回答1:


The strcpy function (which you should never use! -- use strncpy or strdup to avoid buffer overflow vulnerabilities), copies the bytes from one string buffer to the other; assignment changes the buffer to which you are pointing. Note that to invoke strncpy (or strcpy, but don't!) you need to have a buffer already allocated to do this copy. When you do an assignment from a literal string, the compiler has effectively created a read-only buffer, and your pointer is updated with the address of that.

UPDATE

As pointed out in the comments, strncpy has its drawbacks, too. You are much better off using your own helper functions to copy the data from one buffer to another. For example:

ReturnCode CopyString(char* src, char* out, int outlen) {
   if (!src) {
     return NULL_INPUT;
   }
   if (!out) {
     return NULL_OUTPUT;
   }
   int out_index = 0;
   while ((*src != '\0') && (out_index < outlen - 1)) {
     out[out_index++] = *src;
     src++;
   }
   out[out_index] = '\0';
   if (*src != '\0') {
      if (outlen > 0) {
         out[0] = '\0';  // on failure, copy empty rather than partially
      }
      return BUFFER_EXCEEDED;
   }
   return COPY_SUCCESSFUL;
}

And, if you can use C++, not just C, then I would suggest using std::string.



来源:https://stackoverflow.com/questions/41084469/what-is-the-difference-between-strcpy-and

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!