문제

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

도움이 되었습니까?

해결책

The memcpy() function shall copy n bytes from the object pointed to by s2 into the object pointed to by s1. If copying takes place between objects that overlap, the behavior is undefined.

memcpy assumes that the source and destination don't overlap. If they do, anything can happen, and exactly what happens may depend on what compiler you use, what machine you compile or run on, how big the region you're copying is, what time of day it is, etc. If you want to copy a block of memory to a destination overlapping the original position, use memmove.

다른 팁

For memcpy():

[...] If the objects overlap, the behavior is undefined.

You should use memmove() instead for overlapping cases.

[...] The objects may overlap: copying takes place as if the characters were copied to a temporary character array and then the characters were copied from the array to dest.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top