strncpy To strcpy Equivilence in Code

strncpy To strcpy Equivilence in Code

本文关键字:in Code Equivilence strcpy To strncpy      更新时间:2023-10-16

我有这个丑陋的功能,我觉得整个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);
}

cursor保证有足够的空间来包含所有复制的数据。并且data在终止时仅包含一个''字符。

我想更新这个函数以使用strcpy,并删除一些丑陋的东西。这是我所拥有的:

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

我的代码工作正常,但我想问是否有人看到我可能错过的任何不当行为?

编写代码的人都不知道他们在做什么。使用strncpy是没有意义的,因为在调用中传递给它的长度是源的长度,而不是目标。最后的那个reinterpret_cast只是将cursor转换为其原始类型。摆脱这种废话。您的代码是一个很好的替代品。