strcpy和“=”之间有什么区别?

时间:2016-12-11 08:56:29

标签: c strcpy

我想知道char* test = "test"strcpy(test, "test")之间是否存在差异,如果存在差异,那么这种区别是什么。

感谢。

1 个答案:

答案 0 :(得分:1)

strcpy函数(你永远不应该使用它! - 使用strncpystrdup来避免缓冲区溢出漏洞),将字节从一个字符串缓冲区复制到其他;赋值更改您指向的缓冲区。请注意,要调用strncpy(或strcpy,但不要!),您需要已经分配了一个缓冲区来执行此复制。当您从文字字符串进行赋值时,编译器已有效地创建了一个只读缓冲区,并使用该地址更新指针。

<强>更新

正如评论中所指出的,strncpy也有其缺点。最好使用自己的辅助函数将数据从一个缓冲区复制到另一个缓冲区。例如:

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;
}

而且,如果您可以使用C ++,而不仅仅是C,那么我建议使用std::string

相关问题