首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> 關於C

C語言手寫標準庫:memmove 支援重疊記憶體複製實作

     編輯:關於C

memmove vs memcpy 關鍵差異

memmove 保證重疊來源/目的區域正確複製,內部自動選擇複製方向。

正確手寫實作

#include 
#include 

void *my_memmove(void *dest, const void *src, size_t n) {
    assert(dest && src);
    char *d = (char *)dest;
    const char *s = (const char *)src;
    char *ret = d;
    
    if (d > s && d < s + n) { // 目的在來源後方且重疊 -> 從後向前複製
        d += n; s += n;
        while (n--) *--d = *--s;
    } else { // 否則從前向後 (含不重疊、目的在前)
        while (n--) *d++ = *s++;
    }
    return ret;
}

原始碼錯誤分析

dest = dest + 16; src = src + 8; // 硬編碼偏移,完全錯誤!
if ((src < dest) && (dest < src + count)) ...
  • 任意修改 dest/src 指針導致邏輯混亂、回傳值錯誤。
  • 判斷重疊條件寫法不標準。

測試重疊案例

int main() {
    int arr[] = {1,2,3,4,5,6,7,8,9,10};
    // 將前 5 個複製到索引 2 開始 (重疊)
    my_memmove(arr+2, arr, 5*sizeof(int));
    // 正確結果: 1 2 1 2 3 4 5 8 9 10
    for (int i=0;i<10;i++) printf("%d ", arr[i]);
    return 0;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved