0

Right, so I'm playing around with memory moving data around. I'm having trouble here. What can I be doing wrong? I've accounted for the null terminator and it still doesn't output what I expect.

char buff[34] = "I will not do anything like that.";
char * protocol = "abcdefghi";

char data[44];

memcpy(data, protocol, 10);
memcpy(data + 9, buff, 34);

cout << data << endl; //abcdefghiI will not do anything like that.
cout << strlen(data) << endl; // 42

char poin[10];
memcpy(poin, data, 10);

cout << poin << endl; //abcdefghiI╠╠╠╠╠╠╠╠╠╠abcdefghiI will not do anything like that.

For the last cout I was expecting just abcdefghi, but it comes out as you see above. Any help is appreciated, thanks!

user1255454
  • 669
  • 1
  • 8
  • 18

3 Answers3

1

poin is not a '\0'-terminated string. You overwrote the first '\0' with 'I' here:

memcpy(data + 9, buff, 34);
Alexey Frunze
  • 61,140
  • 12
  • 83
  • 180
1

Because poin is not null-terminated. You copied the beginning 10 bytes of data into poin, so now

poin[0] == 'a'
poin[1] == 'b'
poin[2] == 'c'
poin[3] == 'd'
poin[4] == 'e'
poin[5] == 'f'
poin[6] == 'g'
poin[7] == 'h'
poin[8] == 'i'
poin[9] == 'I'

Then, std::cout went outside the array poin's boundary, and the values in those addresses are indeed unknown.

timrau
  • 22,578
  • 4
  • 51
  • 64
0

The last memcpy doesn't include the '\0' used to terminate C style strings.

You would be much better off using strcpy, or when using C++ - std::string.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203