Search code examples
c++cstandard-library

Is strncpy() a specialization of memcpy()?


Just curious to know (as we use these functions often). I don't see any practical difference between strncpy() and memcpy(). Isn't it worth to say that effectively,

char* strncpy (char *dst, const char *src, size_t size)
{
  return (char*)memcpy(dst, src, size);
}

Or am I missing any side effect? There is one similar earlier question, but couldn't find an exact answer.


Solution

  • There is a difference, see this part of the strncpy page you linked to (emphasis mine):

    Copies the first num characters of source to destination. If the end of the source C string (which is signaled by a null-character) is found before num characters have been copied, destination is padded with zeros until a total of num characters have been written to it.

    So if the string to be copied is shorter than the limit, strncpy pads with zero while memcpy reads beyond the limit (possibly invoking undefined behaviour).