有过C语言编程的朋友应该都有过指针越界的困扰。不管越界的地方是全局地址、还是局部地址,查起来都是非常麻烦,原因大多时候都来自于自己对char数组类型的误用。很多同学可能都不是很清楚,在str系类的函数中,函数会在结尾的时候添加NULL指针。比如说strncpy函数,在linux kernel上是这样写的

/**
 * strncpy - Copy a length-limited, %NUL-terminated string
 * @dest: Where to copy the string to
 * @src: Where to copy the string from
 * @count: The maximum number of bytes to copy
 *
 * The result is not %NUL-terminated if the source exceeds
 * @count bytes.
 */
char * strncpy(char * dest,const char *src,size_t count)
{
 char *tmp = dest;

 while (count) {
  if ((*tmp = *src) != 0) src++;
  tmp++;
  count--;
 }
 return dest;
}
 


  而memmove函数是这样描写的

/**
 * memmove - Copy one area of memory to another
 * @dest: Where to copy to
 * @src: Where to copy from
 * @count: The size of the area.
 *
 * Unlike memcpy(), memmove() copes with overlapping areas.
 */
void * memmove(void * dest,const void *src,size_t count)
{
 char *tmp, *s;

 if (dest <= src) {
  tmp = (char *) dest;
  s = (char *) src;
  while (count--)
   *tmp++ = *s++;
  }
 else {
  tmp = (char *) dest + count;
  s = (char *) src + count;
  while (count--)
   *--tmp = *--s;
  }

 return dest;
}
 


  通过上面的代码,我们发现memmove函数有几个好处:

  (1)会根据dest和src的地址关系灵活判断复制顺序;

  (2)不会额外添加NULL指针;

  (3)需要自己时刻关心当前字符串的大小问题;

  (4)memmove可以应用于各种数据结构,而不仅仅是char*类型。