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 thememcpy()
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?
From the comments your problem is that you don't understand what "overlapping" means:
Overlapping means this:
Here the two memory regions
src
anddst
do overlap:But here they don't:
So if you have overlapping memory regions, then you cannot use
memcpy
but you have to usememmove
.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.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.*) 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 :
if i do the following operations separately,
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,
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