Compare the usage of strncpy with snprintf

  • 2020-04-02 01:11:17
  • OfStack

Proper use of strncpy:
Strncpy (dest, SRC, sizeof (dest));
Dest [sizeof (dest) - 1] = '\ 0';

Proper use of snprintf:
Snprintf (dest, sizeof (dest), "% s", SRC);

Strncpy problem:
Size must be sizeof(dest) or sizeof(dest)-1, and sizeof(SRC) must not be misused.
Be sure to manually set the last byte of dest to 0. Because strncpy only fills in zeros for the remaining bytes if the length of SRC is less than dest.
3. Performance issues. When the dest length is much larger than SRC, there is a significant performance penalty because strncpy fills in zeros for every extra byte.
Return value. Strncpy returns dest, so there is no way to know how many bytes have been copied.

Snprintf problems:
1. Do not omit the third parameter "%s". The danger is that if % is included in SRC, core will be triggered.
2. Performance issues. When the SRC length is much longer than dest, there is a significant performance penalty due to the number of bytes that snprintf returns to the SRC and the need to scan the SRC.
3. Return value. If the current buf is sufficient, return the number of characters actually written; If insufficient, returns the number of characters to be written. In other words, the return value is the number of characters passed in.

Conclusion:
1. Snprintf is simpler to use than strncpy.
2. Snprintf can get the number of bytes copied.
Both have performance problems. If SRC is much larger than dest, use strncpy; If dest is much larger than SRC, use snprintf.


Related articles: