Meaning of overlapping when using memcpy

2019-01-15 21:33发布

I am trying to understand the function memcpy() which is defined in the C library <string.h>

Syntax: void *memcpy(void*dst,const void*src,size_t n);

I know that this function is used to copy the contents of the memory pointed by pointer src to the location pointed by the dst pointer and return a address pointed by dst pointer.

I am not able to understand the following important statement regarding memcpy():

  • When using memcpy(), memory address should not overlap, if it overlaps then the memcpy() is undefined.

Another query is: Is the value passed to third argument of the function i.e size_t n is always an integer value?

标签: c overlap memcpy
3条回答
做个烂人
2楼-- · 2019-01-15 21:43

From the comments your problem is that you don't understand what "overlapping" means:

Overlapping means this:

Here the two memory regions src and dst do overlap:

enter image description here

But here they don't:

enter image description here

So if you have overlapping memory regions, then you cannot use memcpy but you have to use memmove.


Second question:

Yes, size_t is an unsigned integer type. The third argument is the number of bytes to copy, so it can hardly be anything else than an unsigned integer type.

查看更多
我命由我不由天
3楼-- · 2019-01-15 21:53

memcpy doesn't use any temporary memory to copy from src to dst.

Let say:

  • src starts @104
  • dst starts @108
  • src = "abcdefgh"

Then 'a' will be @104 and 'e' will be @108.

Assuming char as 1 byte then after copying:

  • dst = "abcdabcd".

As n denotes length to be copied, it should always be an integer.

To copy overlapping areas, you can use memmove function which uses temporary memory to copy.

查看更多
我只想做你的唯一
4楼-- · 2019-01-15 21:53

*) The main difference between memcpy and memmove is,memcpy works on the same string but memmove works in separate memory by taking a copy of the string.
*) Due to this,overlapping happens in memcpy.
Let me explain you with an example.
I took a character array :

char s[20]="alightechs";

if i do the following operations separately,

memmove(s+5,s,7);  
memcpy(s+5,s,7); 



o/p for memmove is alighalighte  
o/p for memmove is alighalighal  

because moving or copying both happens single byte by byte.
till alighaligh, there is no problem in both the cases because dest=alighte(7 is the number of chars to copy/move),
while memcpy i'm copying from 5th position,

alightechs   
alighaechs  
alighalchs  
alighalihs  
alighaligs  
alighaligh  

till here there is no problem,it copied aligh(5 letters)
as,memcpy works on the same string,6th letter will be a and 7th letter will be l
i.,e every time the string is getting updated which results in undefined o/p as below
at 6th letter copying,
the updated string is s[20]=alighaligh
so we get now

alighaligha  
alighalighal  
查看更多
登录 后发表回答