Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

snprintf vs. strcpy (etc.) in C

Tags:

c

string

printf

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?

like image 514
monkeyking Avatar asked Apr 09 '10 10:04

monkeyking


People also ask

Why strcpy is not safe?

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.

What is the difference between strcpy and Strlcpy?

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.

Is Snprintf unsafe?

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.

Is Snprintf slow?

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.


1 Answers

As others did point out already: Do not use strncpy.

  • strncpy will not zero terminate in case of truncation.
  • strncpy will zero-pad the whole buffer if string is shorter than buffer. If buffer is large, this may be a performance drain.

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.

like image 195
Thomas Stuefe Avatar answered Sep 21 '22 21:09

Thomas Stuefe