user1255454
user1255454

Reputation: 699

Memory manipulating - what am I doing wrong?

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!

Upvotes: 0

Views: 74

Answers (3)

timrau
timrau

Reputation: 23058

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.

Upvotes: 1

Bo Persson
Bo Persson

Reputation: 92341

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.

Upvotes: 0

Alexey Frunze
Alexey Frunze

Reputation: 62106

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

memcpy(data + 9, buff, 34);

Upvotes: 1

Related Questions