Martin Ueding Martin Ueding - 13 days ago 4x
C Question

Can memcpy or memmove return a different pointer than dest?

The function

is defined like this:

void *memmove(void *dest, const void *src, size_t n);

In the Linux manual page, it says:


The memmove() function returns a pointer to dest.

Why isn't the function just defined as
void memmove(…)
when it always returns one of the input parameters? Can the return value be different from

Or is the return value really always
and it is just done to be able to compose the function in some creative ways?


memmove will never return anything other than dest.

Returning dest, as opposed to making memmove void, is useful when the first argument is a computed expression, because it lets you avoid computing the same value upfront, and storing it in a variable. This lets you do in a single line

void *dest = memmove(&buf[offset] + copiedSoFar, src + offset, sizeof(buf)-offset-copiedSoFar);

what you would otherwise need to do on two lines:

void *dest = &buf[offset] + copiedSoFar;
memmove(dest, src + offset, sizeof(buf)-offset-copiedSoFar);