Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memcpy copying partly over itself

Tags:

c

memcpy

Is this ok?

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

Does having a bigger datatype make any difference? I know I could use memmove(), but I'm just curious.

like image 709
Stockhausen Avatar asked Mar 15 '11 11:03

Stockhausen


People also ask

Can memcpy overwrite?

One of those is the memcpy() family of functions, which are used to efficiently copy or overwrite blocks of memory; with a bit of help from the compiler, those functions can be prevented from writing past the end of the destination object they are passed.

Does memcpy overwrite or append?

memcpy replaces memory, it does not append.

Does memcpy copies byte by byte?

memcpy() — Copy Bytes Threadsafe: Yes. The memcpy() function copies count bytes of src to dest . The behavior is undefined if copying takes place between objects that overlap.

Why is memcpy faster than Strcpy?

If you know the length of a string, you can use mem functions instead of str functions. For example, memcpy is faster than strcpy because it does not have to search for the end of the string. If you are certain that the source and target do not overlap, use memcpy instead of memmove .


2 Answers

The effects of memcpy are not defined when the input and output overlap. You should use memmove.

like image 167
Gareth McCaughan Avatar answered Oct 12 '22 03:10

Gareth McCaughan


Not okay. You must use memmove when the source and destination overlap.

It might work with memcpy, depending on your compiler's implementation, but that is not something you should rely on!


A typical naive implementation might be a byte-by-byte copy (uint8) like this:

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;
}

which would work okay with your memcpy(buf, buf + 1, 2), but less well with memcpy(buf + 1, buf, 2)

like image 30
GrahamS Avatar answered Oct 12 '22 03:10

GrahamS