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.
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.
memcpy replaces memory, it does not append.
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.
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 .
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With