Memcpy copying partially over itself

This is normal?

char buf[] = { 0, 1, 2 };
memcpy(buf, buf + 1, 2);

Does the data type make any difference? I know I can use memmove (), but I'm just curious.

+5
source share
4 answers

Effects are memcpynot detected when input and output overlap. You must use memmove.

+12
source

Not okay. You must use memmovewhen overlapping the source and destination.

It may work with memcpy, depending on your compiler implementation, but that’s not what you should rely on!


A typical naive implementation might be a byte copy (uint8) as follows:

typedef unsigned char uint8;

void * memcpy ( void * destination, const void * source, size_t num )
{
    const uint8* pSrc = (const uint8*)source;
    const uint8* const pSrcEnd = pSrc + num;
    uint8* pDst = (uint8*)destination;

    while (pSrc != pSrcEnd)
        *(pDst++) = *(pSrc++);

    return destination;
}

memcpy(buf, buf + 1, 2), memcpy(buf + 1, buf, 2)

+5

undefined, , .

+3

undefined, ,

char buf[] = {0, 1, 2, 3);
memcpy(buf, buf+2, 2);

where the endpoint of the destination is less than the starting point of the source. You should still use memmove to be sure ...

+1
source

All Articles