1. 程式人生 > >Strcpy函數的實現

Strcpy函數的實現

span tmp const void color 程序崩潰 bsp != memmove

(1)strcpy函數沒有處理內存重疊的情況,所以內存重疊時使用這個函數會讓程序崩潰

函數原型為:

char * strcopy(char *dst, char *src, int n)

{

  char *addr = dst;

  assert((dst != NULL) && (src != NULL) );

  while((*dst++ = *src++) != ‘\0‘)

  NULL;

  return addr ;

}

(2)memcpy也沒有考慮到內存重疊

void *memcpy(void *dst, void *source, int count)

{

  char *tmp_dest = (char *)dest;
  char *tmp_source = (char *)source;

  assert((dst != NULL) & (src != NULL));

  while(count--)

  {

    *tmp_dest ++ = *tmp_source ++;

  }

  return dest;

}

(3)memmove考慮到了內存重疊的情況

 1 void *memmove(void *dest, const void *source, size_t count)
 2 {
 3   assert((NULL != dest) && (NULL != source));
 4   char *tmp_source, *tmp_dest;
5   tmp_source = (char *)source; 6   tmp_dest = (char *)dest;
7   if((dest + count < source) || (source + count) < dest)) 8   {  // 如果沒有重疊區域 9     while(count--) 10     *tmp_dest++ = *tmp_source++; 11   } 12   else 13   { //如果有重疊(反向拷貝) 14     tmp_source += count - 1; 15     tmp_dest += count - 1
; 16     while(count--) 17       *--tmp_dest = *--tmp; 18   } 19     return dest; 20 }

Strcpy函數的實現