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

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

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
    memm
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值