简体   繁体   English

memcpy function 定义中缓冲区的重叠是什么意思?

[英]What does overlapping of buffer mean in memcpy function definition?

The function definition of memcpy reads as below - memcpy 的 function 定义如下 -

The memcpy function copies size bytes from the object beginning at from into the object beginning at to. memcpy function 将 size 字节从 object 开始复制到 object 开始 at to。 The behavior of this function is undefined if the two arrays to and from overlap;如果两个 arrays 往来重叠,则此 function 的行为未定义; use memmove instead if overlapping is possible.如果可能重叠,请改用 memmove。

What does arrays "to" and "from" overlap mean? arrays“to”和“from”重叠是什么意思? When do we say two array overlap?我们什么时候说两个数组重叠?

Usually, we think of something to be overlapping when it is of the scenario - "to" array starts at an address 1000 and has a size of 100 and "from" array starts at an address 1050 and has a size of 100.通常,我们认为在场景中有些东西是重叠的——“to”数组从地址 1000 开始,大小为 100,“from”数组从地址 1050 开始,大小为 100。

But this can't happen, since the system does not allocate the memory for "from" array at 1050, since "to" array has been already allocated the location between 1000 to 1100.但这不可能发生,因为系统没有为 1050 处的“from”数组分配 memory,因为“to”数组已经分配了 1000 到 1100 之间的位置。

This would be an overlap:这将是一个重叠:

char arr[10];
// Code that does something
memcpy(&arr[0], &arr[3], 5);

But this would not:但这不会:

memcpy(&arr[0], &arr[3], 2);

If you have two char pointers, p and q and you call memcpy(p, q, size) , then an overlap means that there is at least one byte that belongs to both the interval [p,p+size] and [q,q+size] .如果您有两个 char 指针pq并调用memcpy(p, q, size) ,则重叠意味着至少有一个字节同时属于区间[p,p+size][q,q+size] In the above example, those elements are arr[3] and arr[4] .在上面的示例中,这些元素是arr[3]arr[4]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM