C++ 代码中strncpy与strcpy的等效性
我有这个丑陋的函数,我觉得整个C++ 代码中strncpy与strcpy的等效性,c++,string,strcpy,code-cleanup,strncpy,C++,String,Strcpy,Code Cleanup,Strncpy,我有这个丑陋的函数,我觉得整个strncpy应该只是一个strcpy: void PackData(char*& cursor, const std::string& data) { *(reinterpret_cast<int*>(cursor)) = static_cast<short>(data.length() + 1); cursor += sizeof(int); // copy the text to the buff
strncpy
应该只是一个strcpy
:
void PackData(char*& cursor, const std::string& data) {
*(reinterpret_cast<int*>(cursor)) = static_cast<short>(data.length() + 1);
cursor += sizeof(int);
// copy the text to the buffer
::strncpy(cursor, data.c_str(), data.size());
cursor += (data.length() * sizeof(char));
*(reinterpret_cast<char*>(cursor)) = 0;
cursor += sizeof(char);
}
我的代码运行良好,但我想问是否有人看到了我可能错过的任何不当行为?编写代码的人都不知道他们在做什么。使用
strncpy
毫无意义,因为调用中传递给它的长度是源的长度,而不是目标的长度。最后的reinterpret_cast
只是将cursor
转换为其原始类型。别胡说八道了。你的代码是一个很好的替代品 嗯,出于这样的目的,不知何故,我觉得memcpy
会更好。我不得不承认这很难看。这让我怀疑,写这篇文章的人是否对越界写作的可能性过于敏感。并不是说它不是非常糟糕,但这是一个非常多的演员和舞蹈的strncpy
memcpy
将更快,因为它不检查'\0'
每个字符,但也可能有点不清楚,因为我复制了一个字符串。我可以选择任何一种方式,但问题仍然是,输出是否一致。@DavidHoelzer甚至在字符串的开头加上int
,而在另一端你可以做strlen
,这种想法都令人恶心。但我不控制这个垃圾信息传递到的模块,所以我只想确保在签入这样的更改之前,我没有忽略任何东西。这似乎属于我,我认为你的回答意味着我的代码应该有相同的行为。@JonathanMee-是的,做吧。我已经相应地编辑了我的答案。很抱歉有点粗心。它不是等效的,也不是一个好的替代品,因为strcpy()复制一个字符more@Slava这就是原始函数插入的意图,即在strncpy
之后插入的'\0'
不会插入终止null。@JonathanMee除非答案被更改,否则我不能
void PackData(char*& cursor, const std::string& data) {
const int size = data.size() + 1;
std::copy_n(cursor, sizeof(int), reinterpret_cast<char*>(&size));
cursor += sizeof(int);
strcpy(cursor, data.c_str());
cursor += size;
}