The third parameter of memcpy(dst,src,len)
gives the number of bytes to copy.
If that number of bytes is bigger than the memory pointed to by either parameter, you are hosed. That's a technical term describing things like the Heartbleed bug, as well as quite a few other bugs I've had the delightful experience :-( of fixing.
If your software development mindset is oriented toward memory objects, the code pattern in your question is valid. For example, if you develop around the idea that you use memcpy()
to make exact copies of entire objects, I suppose you would never use any third parameter besides sizeof(src)
.
But memcpy()
is useful for many other sorts of operations, such as management of partial buffers, gathering disjointed streams of data into consecutive memory locations, and similar things.
It's also subject to misuse, and ordinarily has no checks against that. For example, there are probably tens of thousands of code snippets in the wild, many of them in embedded systems, that look something like this.
char [10] out;
char [] in = "Yo ho ho and a bottle of rum!";
...
memcpy (out, in, 1+ strlen(in)); /*don't do this or you're hosed!*/