Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 代码中strncpy与strcpy的等效性_C++_String_Strcpy_Code Cleanup_Strncpy - Fatal编程技术网

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