memcpy,memmove,bcopy三个函数的内存重叠

本文探讨了memcpy、memmove和bcopy在处理内存重叠时的行为。memcpy在源和目标重叠时行为未定义,而bcopy能正确处理这种情况。尽管在某些系统中memcpy可能表现正确,但其行为并不总是可靠,特别是在内存区域重叠时。通过代码验证,当使用memcpy在destination的第3个位置赋值时,由于内存重叠可能导致数据错误,揭示了内存重叠问题的重要性。

bcopy correctly handles overlapping fields, while the behavior of memcpy is undefined if the source and destination overlap. The ANSI C memmove function must be used when the fields overlap.

在书里看到这两句话的时候挺困惑的,平时用这几个函数也没有留意这个问题,于是写了些代码验证了下这个问题。

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

void main()
{
    int test[10];
    int* source = test;
    int* destination = &test[2];
    int i = 0;
    for (i = 0; i < 10; ++i)
    {   
        test[i] = i;
    }   
    memcpy(destination, source, sizeof(int) * 5); // 0 1 0 1 2 3 4 7 8 9
    memcpy(source, destination, sizeof(int) * 5); // 2 3 4 5 6 5 6 7 8 9
    bcopy(source, destination, sizeof(int) * 5); // 0 1 0 1 2 3 4 7 8 9
    bcopy(destination, source, sizeof(int) * 5); // 2 3 4 5 6 5 6 7 8 9
    memmove(destination, source, sizeof(int) * 5); // 0 1 0 1 2 3 4 7 8 9
    memmove(source, destination, sizeof(int) * 5); // 2 3 4 5 6 5 6 7 8 9
    for (i = 0; i < 10; ++i)
    {   
        printf("%d ", test[i]);
    }   
    printf("\n");
}

乍一看,三个函数的结果都是一样的。那为什么会有上面这两句话呢?于是在网上查了下别人的文章,终于理解了书里说的这两句话到底是什么意思,由于系统的原因,memcpy在这个系统的实现是对的,但是在其它系统上实现有可能就是不对的。

test0123456789
destination  01      

用memcpy对destination上第3个位置赋值的时候,由于test上第3个位置被之前赋值时修改为0,所以destination上的第3个位置有可能会被赋上0,内存重叠的问题就出现了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值