为什么Linux memmove()是按原样实现的? [英] Why is Linux memmove() implemented the way it is?

查看:123
本文介绍了为什么Linux memmove()是按原样实现的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从Linux联机帮助页中获取 memmove(3)

From the Linux manpage for memmove(3)

memmove()函数将n个字节从存储区src复制到存储区dest. 内存区域可能会重叠:复制就好像src中的字节是 首先将其复制到不与src或dest重叠的临时数组中,然后 然后将字节从临时数组复制到dest.

The memmove() function copies n bytes from memory area src to memory area dest. The memory areas may overlap: copying takes place as though the bytes in src are first copied into a temporary array that does not overlap src or dest, and the bytes are then copied from the temporary array to dest.

我们可以执行以下操作,而不是分配一个临时数组并复制两次值:

Instead of allocating a temporary array and copy the values twice we could just do the following:

void *my_memmove(void *dest, const void *src, size_t n) {
  signed char operation;
  size_t end;
  size_t current;

  if(dest != src) {
    if(dest < src) {
      operation = 1;
      current = 0;
      end = n;
    } else {
      operation = -1;
      current = n - 1;
      end = -1;
    }

    for( ; current != end; current += operation) {
      *(((unsigned char*)dest) + current) = *(((unsigned char*)src) + current);
    }
  }
  return dest;
}

在此实现中,我们只需要处理我们开始复制的位置.

In this implementation we simply take care of the position where we begin to copy.

实施中是否有缺点?

注意:我实际上不会使用我的实现.我很好奇.

推荐答案

您可以查看memmove的一些源代码此处

You can look at some source code for memmove here, here, here, and here.

您会注意到,它们实际上并没有建立一个临时数组.编写手册页的目的是帮助您逻辑而不是实际.因此,他们说好像".

What you'll notice is that they don't actually make a temporary array. The man pages are written to help you understand what it is doing logically, not actually. Hence, they say "as though".

memmove()实际执行的操作是将字节从src复制到dest,如果dest < src(与memcpy本质相同),则将其向前复制,否则将其向后复制.

What memmove() actually does is copy the bytes from src to dest, and it copies forward if dest < src (which is essentially the same thing as memcpy), and backwards otherwise.

memcpymemmove之间的区别是memcpy盲目向前复制-这就是为什么destsrc不应重叠的原因.但是memmove采取预防措施,以确保重叠不会破坏最终结果.

The difference between memcpy and memmove is that memcpy blindly copies forward - which is why dest and src should not overlap. But memmove takes the precaution of ensuring the overlap will not screw up the end result.

这篇关于为什么Linux memmove()是按原样实现的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆