memcpy copying partly over itself
Is this ok?
char buf[] = { 0, 1, 2 };
memcpy(b开发者_Python百科uf, buf + 1, 2);
Does having a bigger datatype make any difference? I know I could use memmove(), but I'm just curious.
The effects of memcpy
are not defined when the input and output overlap. You should use memmove
.
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)
The behavior is undefined if the memory regions overlap, so this is not ok.
It is undefined behaviour, but I have used it like so,
char buf[] = {0, 1, 2, 3);
memcpy(buf, buf+2, 2);
where the end point of the destination is less than the start point of the source. You should still use memmove to be sure...
精彩评论