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

sharptooth picture sharptooth · Sep 20, 2010 · Viewed 35.5k times · Source

Do I need to treat cases when I actully have nothing to move/copy with memmove()/memcpy() as edge cases

int numberOfBytes = ...
if( numberOfBytes != 0 ) {
    memmove( dest, source, numberOfBytes );
}

or should I just call the function without checking

int numberOfBytes = ...
memmove( dest, source, numberOfBytes );

Is the check in the former snippet necessary?

Answer

Mike Seymour picture Mike Seymour · Sep 20, 2010

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).