memmove函数:内存重叠时拷贝

最近测试遇到一个memcpy在x86和arm平台上拷贝字节时不一致的问题。出现拷贝是memcpy函数少量字节拷贝错误。

分析

参考:https://blog.csdn.net/shuidaoqingyi520/article/details/131669163
在内存有重合的时候memcpy是不稳定的,要使用memmove函数。我于是自己写了个简单代码对比

#include <stdio.h>
#include <string.h>

#define uint8_t unsigned char

int main() 
{
	// 初始赋值
    uint8_t In[36]={
        1,      2,      3,      4,      5,      6,
        7,      8,      9,      10,     11,     12,
        13,     14,     15,     16,     17,     18,
        19,     20,     21,     22,     23,     24,
        25,     26,     27,     28,     29,     30,
        31,     32,     33,     34,     35,     36
     }; 

    /*for(int i=0; i<36; i++){
        In[i] = i+1;
        printf("%u,",In[i]);
    }*/

    printf("\n src array:\n");
    for(int i=0; i<35; i++){
        printf("%u,",(In+1)[i]);
    }

    // 测试1
    memmove(In, In+1, sizeof(uint8_t)*20);

    // 测试2
    // memcpy(In, In+1, sizeof(uint8_t)*20);
	
	// 测试3
	// uint8_t tmp[36]={0};
    // memcpy(tmp, In+1, sizeof(uint8_t)*20);
    // memcpy(In, tmp, sizeof(uint8_t)*20);

    printf("\n dst array:\n");
    for(int i=0; i<36; i++){
      printf("%u,",In[i]);
    }
    printf("\n");
    return 0;
}

测试结果

不过根据测试结果来看,简单的程序memcpy和memmove还是一样的。

情况1:memmove

# gcc arraycopy.c -o arraycopy
# ./arraycopy
 src array:
2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,
 dst array:
2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,
posted @ 2024-12-26 11:09  liqinglucky  阅读(1)  评论(0编辑  收藏  举报