For doing string concatenation, I've been doing basic strcpy
, strncpy
of char* buffers. Then I learned about the snprintf
and friends.
Should I stick with my strcpy
, strcpy
+ \0
termination? Or should I just use snprintf
in the future?
Problem with strcpy(): The strcpy() function does not specify the size of the destination array, so buffer overrun is often a risk. Using strcpy() function to copy a large character array into a smaller one is dangerous, but if the string will fit, then it will not be worth the risk.
In computer programming, the strlcpy function is intended to replace the function strcpy (which copies a string to a destination buffer) with a secure version that cannot overflow the destination buffer.
Warning: The sprintf function can be dangerous because it can potentially output more characters than can fit in the allocation size of the string s . Remember that the field width given in a conversion specification is only a minimum value. To avoid this problem, you can use snprintf or asprintf , described below.
snprintf is still not fast in general (lots of overhead parsing the format string and passing varargs through wrapper functions). But with that bugfix, it should hopefully scale similarly to large strings as strcpy , or at least as strlen + memcpy which makes two passes over the data.
As others did point out already: Do not use strncpy.
snprintf will (on POSIX platforms) zero-terminate. On Windows, there is only _snprintf, which will not zero-terminate, so take that into account.
Note: when using snprintf, use this form:
snprintf(buffer, sizeof(buffer), "%s", string);
instead of
snprintf(buffer, sizeof(buffer), string);
The latter is insecure and - if string depends on user input - can lead to stack smashes, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With