Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...