strcpy not dangerous as far as you know that the destination buffer is large enough to hold the characters of the original string; otherwise strcpy will gladly copy more characters than your target buffer can hold, which can lead to several unfortunate consequences (rewriting strings and other variables, which can lead to crashes, stack-breaking attacks and co.).
But: if you have a common char * input that has not yet been verified, the only way to make sure is to apply strlen to such a string and check if this is too much for your buffer; however, now you need to go through the entire source line twice, once to check its length, once to make a copy.
This is suboptimal, since if strcpy was a little more advanced, it could get the buffer size as a parameter and stop copying if the source string was too long; in a perfect world, this is how strncpy will execute (following the diagram of other strn*** functions). However, this is not an ideal world, and strncpy not intended for this. Instead, a non-standard (but popular) alternative is strlcpy , which truncates instead of exiting the boundaries of the target buffer.
Several CRT implementations do not provide this function (especially glibc), but you can still get one of the BSD implementations and put it in your application. A standard (but slower) alternative would be to use snprintf with "%s" as the format string.
However, since you are programming in C ++ ( edit , now I see that the C ++ tag has been removed), why don't you just avoid all the errors in the C-string (when you can, obviously) and go with std::string ? All of these potential security issues disappear, and string operations become much simpler.
source share