Open carloscn opened 1 year ago
这道题目需要进行两种情况的分析,分析板书过程如下:
void* utils_memmove(void *dest, const void *src, size_t n)
{
uint8_t *from = (uint8_t *) src;
uint8_t *to = (uint8_t *) dest;
if (from == to || 0 == n) {
return dest;
}
if (to > from && to - from < (int)n) {
/* to overlaps with from */
/* <from......> */
/* <to........> */
/* copy in reverse, to avoid overwriting from */
int32_t i;
for (i = n - 1; i >= 0; i --) {
to[i] = from[i];
}
goto finish;
}
if (from > to && from - to < (int)n) {
/* to overlaps with from */
/* <from......> */
/* <to........> */
/* copy forwards, to avoid overwriting from */
size_t i;
for (i = 0; i < n; i ++) {
to[i] = from[i];
}
goto finish;
}
memcpy(dest, src, n);
finish:
return dest;
}
问题描述
对于man手册中memcpy的接口,有一条这样的说明,https://man7.org/linux/man-pages/man3/memcpy.3.html
memcpy对同一个buffer会出现内存覆盖的现象,请你实现memmove的逻辑,来解决同一个数组的内存覆盖问题。