0

I'm using memcpy to copy a specific number of chars from a char array to a char *. But when I read the char * have always trash in the end.

I'm using libssh2 lib to send commands to my raspberry pi and receive the output.

libssh2_channel_read will return the number of chars of the output int x and the output text will be on the char buffer[32].

Code I'm using:

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 "\r\n"
libssh2_channel_free(channel);
channel = NULL;
cout << output << endl;

Example of output:

0══²²²²

I only want the 0

Samega 7Cattac
  • 253
  • 1
  • 3
  • 16

3 Answers3

9

Welcome to C++.

You are copying the values you care about but not the terminating '\0' character. Assuming x is valid (that is: x > 3 and x <= sizeof(buffer)) you can say:

output[x - 2] = '\0';

after the call to memcpy() and you should get what you expect.

However: when you're dealing with communications and buffers like this you need to be careful and check everything.

janm
  • 17,976
  • 1
  • 43
  • 61
0

I think you shouldn't be using raw arrays and memcpy and the like here.

You are probably better off with the containers from the C++ standard library:

Example:

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';
moooeeeep
  • 31,622
  • 22
  • 98
  • 187
0

Use 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;