strcpy
isn't dangerous as far as you know that the destination buffer is large enough to hold the characters of the source string; otherwise strcpy
will happily copy more characters than your target buffer can hold, which can lead to several unfortunate consequences (stack/other variables overwriting, which can result in crashes, stack smashing attacks & co.).
But: if you have a generic char *
in input which hasn't been already checked, the only way to be sure is to apply strlen
to such string and check if it's too large for your buffer; however, now you have to walk the entire source string twice, once for checking its length, once to perform the copy.
This is suboptimal, since, if strcpy
were a little bit more advanced, it could receive as a parameter the size of the buffer and stop copying if the source string were too long; in a perfect world, this is how strncpy
would perform (following the pattern of other strn***
functions). However, this is not a perfect world, and strncpy
is not designed to do this. Instead, the nonstandard (but popular) alternative is strlcpy
, which, instead of going out of the bounds of the target buffer, truncates.
Several CRT implementations do not provide this function (notably glibc), but you can still get one of the BSD implementations and put it in your application. A standard (but slower) alternative can be to use snprintf
with "%s"
as format string.
That said, since you're programming in C++ (edit I see now that the C++ tag has been removed), why don't you just avoid all the C-string nonsense (when you can, obviously) and go with std::string
? All these potential security problems vanish and string operations become much easier.