7

While reading about memmove I read that it can handle MEMORY OVERLAPSbut I am unable to get how a memmory overlap can occur between two strings and how can this function still copy the block of memory correctly.

2 Answers2

5

"Memory overlap" does not occur by itself. It is you who can supply the memmove function with memory regions that overlap. Take two pointers into the same array and you can easily end up with overlapping memory regions.

Of course, you can also easily create overlapping objects through unions.

It is not clear what you mean by the second part of the question ("how can this function still copy the block of memory correctly"). Where do you see the problem here?

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • I dont get how would a function handle memory overlapping problem –  Sep 03 '10 at 18:14
  • It works as if the source was copied to another buffer, then copied to the destination. Memcpy() copies source to destination directly though. – Jefferson Mar 04 '16 at 04:04
3
 memmove(p+1, p, 42);

Which requires moving the bytes starting at the end. Memcpy() makes a mess of it.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • Strictly speaking, `memcpy` has undefined behavior if used this way. It could conceivably work, for example if it were written assuming backwards copying is faster, or if `memcpy` were just implemented as a call to `memmove`, but you should never rely on such things. :-) – R.. GitHub STOP HELPING ICE Sep 04 '10 at 01:05
  • why would one ever use memcpy if he knows memmove ;) –  Sep 04 '10 at 01:08
  • Does memmove() copy the all the block at once? I mean it takes the block and copies it or copies byte by byte? –  Sep 05 '10 at 07:16
  • Usually 4 bytes at a time, it depends on the implementation. Why don't you just take a look at the source code? – Hans Passant Sep 05 '10 at 07:36