It depends on whether the string to be copied is a literal, as shown, or can vary.
The best technique for the array shown would be:
char arr[128] = "Hello World";
If you're in charge of the string and it contains no %
symbols, then there's not much difference between the two sprintf()
calls. Strictly, the first uses the string as the format and copies the characters directly, while the second notes it has %s
as the format and copies the characters from the extra argument directly — it's immeasurably slower. There's a case for:
snprintf(arr, sizeof(arr), "%s", "Hello World");
which ensures no buffer overflow even if "Hello World" becomes a much longer diatribe.
If you're not in charge of the string, then using snprintf()
as shown becomes important as even if the string contains %
symbols, it is simply copied and there's no overflow. You have to check the return value to establish whether any data was truncated.
Using strcpy()
is reasonable if you know how long the string is and that there's space to hold it. Using strncpy()
is fraught — it null pads to full length if the source is shorter than the target, and doesn't null terminate if the source is too long for the target.
If you've established the length of the string is short enough, using memmove()
or memcpy()
is reasonable too. If the string is too long, you have to choose an error handling strategy — truncation or error.
If the trailing (unused) space in the target array must be null bytes (for security reasons, to ensure there's no leftover password hidden in it), then using strncpy()
may be sensible — but beware of ensuring null termination if the source is too long. In most cases, the initializer for the array is not really needed.
The compiler may be able to optimize the simple cases.