strcpy – Copies the content pointed by src to dest stopping after the terminating null-character is copied.
dest should have enough memory space allocated to contain src string.
strncpy – Copies the first num characters of src to dest.
No null-character is implicitly appended to dest after copying process. So dest may not be null-terminated if no null-caracters are copied from src.
If num is greater than the length of src, dest is padded with zeros until num.
Now, maybe I just dont know, but why would you use strcpy when strncpy is available? I guess I really havent found a solid answer. I mean what were they thinking with strcpy? Were they just trying to create an easy way to have buffer overflows all over? (Same goes for strcat and strncat). I guess I am glad now to use C# and VB.net the majority of the time when you really don’t have to worry about this stuff. With C/C++ its all over the place, and you can tell, just look at all the buffer overflow vulnerabilites withing Microsoft products.
3 replies on “strcpy vs. strncpy”
History lesson time: strcpy (strcat, strlen, et al) came first in the stdlib spec. But then people realized how easy it was to overflow all of those, so the “n” versions were added to the spec. The non-“n” versions have been deprecated for more years than you or I have been programming (yes, it’s been THAT long), but people still use them because of all the examples/habit which built up over the years.
Always use the n versions.
LikeLike
There are still valid and safe ways to use the ‘non n functions’. For example it is perfectly acceptable to use strcpy in scenarios where the source string is static and of a known length. Alternatively it can be used safely with dynamic memory allocation where the length of a string has been calculated and sufficient memory to copy it has been allocated.
LikeLike
most loops check to see if they are at the end of the string when they hit the null terminator, also strcpy is used always used instead of strncpy when converting a C++ string to a C style string because it requires a null terminator REQUIRES a null terminator. Reasons why u would need a C style string are for certain functions to work properly in C++ such as certain constructors for output iterators
LikeLike