I'm playing with memcpy
in order to acquire better perception of its work and i've run into things i can't understand.
I start from very simple piece of code:
char str [] = "0123456789abcdef";
memcpy(str + 5, str, 5);
puts(str);// prints 0123401234abcdef
that's absolutely understandable for me. Then i move on:
char str [] = "0123456789abcdef";
memcpy(str + 5, str, 6);
puts(str); // 01234012340bcdef
at first i expected the output to be 01234012345bcdef
assuming that the function will take first six characters but it started from 0 again. Ok, thought i, probably it somehow takes characters from already built new string. And putting 7 like this memcpy(str + 5, str, 7);
confirmed this my assumption because it had produced 012340123401cdef
as output.
But then things started to get more unclear. If i do this memcpy(str + 5, str, 8);
it outputs 0123401234567def
!!!. Just like i expected from the beginning.
I'm totally confused. Why it behaves this way? Ok, i can even understand printing 01 as 11th and 12th characters of the string (but this is not what i expected and i would be grateful for an explanation). But why when i determine the length as 8 it changes its behaviour???
I hope you understand what i mean. Please provide a detailed explanation. Thanks a lot in advance