使用内存的垃圾

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;