如何在 c++ 中复制包含空终止符的内存块
How to copy a block of memory containing null terminator in c++
我已经在C#中将图像转换为字节数组,并通过TCP将其发送到用C++编写的服务器应用程序。
现在我想将此字节数组复制到另一个内存块。我已经尝试memcpy()
函数,但问题是memcpy
复制内存块,直到它到达空终止符("\0"),并且字节数组包含许多空终止符,我也希望复制它们。
更新
为简单起见,我使用以下语句将 C# 中的字符串 "Hello\0"World\0" 转换为字节数组:
string s = "Hello "World ";
byte[] bytes = Encoding.UTF8.GetBytes(s);
我在 c++ 中接收无符号 char* 中的字节并将其复制到另一个 char 指针,如下所示:
char *chars = new char[12];
memcpy(chars , recvChar, MESSAGE_12);
但字符*导致"你好";
根据这个
函数 memcpy()
不检查源中的任何终止空字符 - 它总是精确地复制字节数。你确定是渺蹊的?
您可以使用这样的东西来打印字符数组(printf 终止于 NULL 字符):
for (int i = 0; i < 12; i++) //12 is the size of chars, I assume
{
if (chars[i]!=NULL) //if you hit a ' ', ignore it
printf("%c", chars[i]);
}
相关文章:
- 将字符串存储在c++中的稳定内存中
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- Win32编译器选项和内存分配
- 当vector是tje全局变量时,c++中vector的内存管理
- 带内存和隔离功能的SQLite
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- C++ 程序不会因为内存而终止
- 检测到由于操作系统内存不足而导致子进程终止
- c++ 终止程序的内存泄漏何时重要?
- 如何在 c++ 中复制包含空终止符的内存块
- 在动态内存分配中,在程序终止并且忘记释放内存后,该内存是否保持分配状态
- 当给出进程的终止命令时,如何处理分配的内存
- 变量或对象的内存在程序结束时自动终止,而不是使用析构函数
- 程序终止后动态分配的内存
- 内存管理 - C++错误:抛出"std::bad_alloc"实例后调用终止
- 程序以信号 25 终止,时间 = 0.06 秒内存 = 3340KB
- 如果应用程序存在内存泄漏,是否在终止时解决这些问题
- 在不终止程序的情况下将动态分配的内存返回给操作系统