I have this ugly function, and I feel that the entire strncpy
should just be an 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
is guaranteed to have enough room to contain all the data copied. And data
only contains a '\0'
character at termination.
I want to update this function to use strcpy
, and to remove some of the ugly. Here's what I have:
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;
}
My code works fine, but I wanted to ask if anyone sees any misbehavior that I may have missed?