c++ - strncpy() 是 memcpy() 的特例吗?

标签 c++ c standard-library

只是想知道(因为我们经常使用这些功能)。我看不出 strncpy() 之间有任何实际区别。和 memcpy() .难道不值得这么有效地说吗,

char* strncpy (char *dst, const char *src, size_t size)
{
  return (char*)memcpy(dst, src, size);
}

还是我遗漏了任何副作用?有一个类似的earlier question , 但找不到确切的答案。

最佳答案

有区别,请参阅您链接到的 strncpy 页面的这一部分(强调我的):

Copies the first num characters of source to destination. If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num characters have been written to it.

因此,如果要复制的字符串比限制短,strncpy 将用零填充,而 memcpy 读取超出限制(可能调用未定义的行为)。

关于c++ - strncpy() 是 memcpy() 的特例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6509449/

相关文章:

c - 在 C 函数中,char 和 string 有什么区别?

c - 在包装函数和局部变量破坏中使用 setjmp

c - stdin 允许读取 EOF 标志集

c++ - 在内存分配方面哪个更好 - 子对象或指向单独对象的指针?

c++ - 在 Linux 中清理无限循环应用程序的正确方法是什么?

c++ - 为什么 GDB(或任何调试器)进入 header ?

c - 如何以编程方式获取二维数组中元素的相邻元素?

c++ - 开场流量不好?

android - 我需要 Hyper-V 才能从 Visual Studio 2015 中调试我的 Android 应用程序吗?

c++ - 错误 C2059 : syntax error : 'constant'