使用内存的垃圾
Trash using memcpy
本文关键字:内存 更新时间:2023-10-16
我正在使用memcpy将特定数量的字符从字符数组复制到字符*。但是当我读到字符*时,最后总是垃圾。
我正在使用 libssh2 lib 向我的树莓派发送命令并接收输出。
libssh2_channel_read
将返回输出int x
的字符数,输出文本将在char buffer[32]
上。
我正在使用的代码:
char buffer[32];
int x = libssh2_channel_read(channel, buffer, sizeof(buffer));
char * output = (char *)malloc(sizeof(char)*x);
memcpy(output, buffer, x-2); // x - 2 because of "rn"
libssh2_channel_free(channel);
channel = NULL;
cout << output << endl;
输出示例:
0══²²²²
我只想要0
欢迎来到C++。
您正在复制您关心的值,而不是终止的"\0"字符。假设x
是有效的(即:x> 3 和 x <= sizeof(buffer)),你可以说:
output[x - 2] = ' ';
打电话给memcpy()
之后,你应该得到你所期望的。
但是:当您处理此类通信和缓冲区时,您需要小心并检查所有内容。
我认为你不应该在这里使用原始数组和memcpy
等。
使用C++标准库中的容器可能会更好:
- http://en.cppreference.com/w/cpp/container/vector
- http://en.cppreference.com/w/cpp/string/basic_string
- 直接写入 std::string 的 char* 缓冲区
例:
std::vector<char> buffer(32);
int x = libssh2_channel_read(channel, &buffer[0], buffer.size());
// probably x will be smaller or equal the current size of the buffer
buffer.resize(x);
// if it's a string, why not have it as a std::string
std::string data(buffer.begin(), buffer.end());
std::cout << data << 'n';
使用 std::string:
char buffer[32];
int x = libssh2_channel_read(channel, buffer, sizeof(buffer));
std::string output{ buffer, buffer + x - 2 };
libssh2_channel_free(channel);
channel = NULL;
cout << output << endl;
相关文章:
- 将字符串存储在c++中的稳定内存中
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- Win32编译器选项和内存分配
- 当vector是tje全局变量时,c++中vector的内存管理
- 带内存和隔离功能的SQLite
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 迭代时从向量和内存中删除对象
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 为什么示例代码访问IUnknown中已删除的内存
- 如何在C++类内存结构中创建"spacer"?
- 从构造函数抛出异常时如何克服内存泄漏
- malloc() 可能出现内存泄漏
- 如何理解将半精度指针转换为无符号长指针和相关的内存对齐
- 在调用FreeLibrary后,释放动态链接到具有相同版本的CRT堆的DLL的内存
- 如何针对特定情况调试和修复此双自由内存损坏问题
- 类型总是使用其大小存储在内存中吗
- 有没有一种方法可以测量c++程序的运行时内存使用情况
- 有没有一种方法可以使用placement new将堆叠对象分配给分配的内存