Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I call memcpy() and memmove() with "number of bytes" set to zero?

People also ask

What is the difference between the functions Memmove () and memcpy ()?

Answer: memcpy() function is is used to copy a specified number of bytes from one memory to another. memmove() function is used to copy a specified number of bytes from one memory to another or to overlap on same memory.

Does memcpy copy byte by byte?

memcpy() — Copy BytesThe memcpy() function copies count bytes of src to dest . The behavior is undefined if copying takes place between objects that overlap. The memmove() function allows copying between objects that might overlap.

Which is faster memcpy or Memmove?

"memcpy is more efficient than memmove." In your case, you most probably are not doing the exact same thing while you run the two functions. In general, USE memmove only if you have to. USE it when there is a very reasonable chance that the source and destination regions are over-lapping.

Can you memcpy null?

memcpy can happen with _first_group as a null pointer and count 0 . Passing null to the second argument is an undefined behavior, even if count is zero.


From the C99 standard (7.21.1/2):

Where an argument declared as size_t n specifies the length of the array for a function, n can have the value zero on a call to that function. Unless explicitly stated otherwise in the description of a particular function in this subclause, pointer arguments on such a call shall still have valid values, as described in 7.1.4. On such a call, a function that locates a character finds no occurrence, a function that compares two character sequences returns zero, and a function that copies characters copies zero characters.

So the answer is no; the check is not necessary (or yes; you can pass zero).


As said by @You, the standard specifies that the memcpy and memmove should handle this case without problem; since they are usually implemented somehow like

void *memcpy(void *_dst, const void *_src, size_t len)
{
    unsigned char *dst = _dst;
    const unsigned char *src = _src;
    while(len-- > 0)
        *dst++ = *src++;
    return _dst;
}

you should not even have any performance penality other than the function call; if the compiler supports intrinsics/inlining for such functions, the additional check may even make the code a micro-little-bit slower, since the check is already done at the while.