Reputation:
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()
:
memcpy()
, the memory address should not overlap, if it overlaps then the memcpy()
is undefined.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
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
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:
But here they don't:
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
Reputation: 31
memcpy
doesn't use any temporary memory to copy from src to dst.
Let say:
src
starts @104dst
starts @108src = "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