strncpy To strcpy Equivilence in Code
strncpy To strcpy Equivilence in Code
我有这个丑陋的功能,我觉得整个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
转换为其原始类型。摆脱这种废话。您的代码是一个很好的替代品。
相关文章:
- netcat command in c++
- Difference in displaying cv2 Mat
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- Visual Studio Code - C++ Debugger 無法啟動
- Visual Studio Code "undefined reference to `WinMain@16'"
- C++ MFC Libraries in Travis CI
- 如何在OpenSSL中从configuration.h.in获取configuration.h
- VS Code "command":"make"与终端窗口中的命令行"make"不同
- 使用VS Code和CMake Tools运行自定义命令
- 修改 VS Code 中的默认C++代码段
- 创建具有 new in 函数和"this is nullptr"异常的对象
- IN, OUT, INOUT Parameters
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- SWIG - C++ code in python
- strncpy To strcpy Equivilence in Code
- OTL 4.0 in code::Block
- In code-删除包含文件的文件夹
- 避免"pointer cannot be null in well-defined C++ code"的投射策略
- C++ Armadillo code in C#
- 谷歌模拟的EXPECT_CALL导致"unknown file:error: SEH exception with code 0xc0000005 thrown in the test body"