user4722851
user4722851

Reputation:

Meaning of overlapping when using memcpy

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 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 the address pointed by dst.

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

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

Upvotes: 4

Views: 10515

Answers (3)

krish sai
krish sai

Reputation: 1

*) 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  

Upvotes: -1

Jabberwocky
Jabberwocky

Reputation: 50831

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.

Upvotes: 16

urvi_189
urvi_189

Reputation: 31

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.

Upvotes: 3

Related Questions