Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can memcpy or memmove return a different pointer than dest?

The function memmove is defined like this:

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

In the Linux manual page, it says:

RETURN VALUE
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 dest?

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

like image 365
Martin Ueding Avatar asked Oct 12 '16 13:10

Martin Ueding


People also ask

What does memmove return?

In the C Programming Language, the memmove function copies n characters from the object pointed to by s2 into the object pointed to by s1. It returns a pointer to the destination. The memmove function will work if the objects overlap.

What library is Memmove in?

C library function - memmove() The C library function void *memmove(void *str1, const void *str2, size_t n) copies n characters from str2 to str1, but for overlapping memory blocks, memmove() is a safer approach than memcpy().

What is Memmove?

memmove() is used to copy a block of memory from a location to another. It is declared in string.h. // Copies "numBytes" bytes from address "from" to address "to" void * memmove(void *to, const void *from, size_t numBytes);


1 Answers

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); 
like image 106
Sergey Kalinichenko Avatar answered Sep 19 '22 10:09

Sergey Kalinichenko