Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
426 views
in Technique[技术] by (71.8m points)

c - 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 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...