Correct usage of strncpy:
strncpy (dest, SRC, sizeof (dest));
Dest[sizeof (dest)-1] = ';
Correct usage of snprintf:
snprintf (dest, sizeof (dest), "%s", SRC);
STRNCPY's Problem:
1.size must use sizeof (dest) or sizeof (dest)-1, not misused sizeof (SRC).
2. Fill in 0 by hand. Be sure to manually set the last byte of dest to 0. Because strncpy only 0 of the remaining bytes when the length of SRC is less than dest.
3. Performance problems. When the dest length is much larger than SRC, the strncpy will have a significant performance penalty because it fills in 0 of the extra bytes.
4. Return value. strncpy returns DEST, so it is impossible to know how many bytes were copied.
Snprintf's Problem:
1. Cannot omit the third parameter "%s", the hidden danger is that if the SRC contains%, it will cause core.
2. Performance problems. When the src length is much larger than the dest, because the snprintf to return the number of src bytes, the need to scan SRC, there will be a great loss of performance.
3. return value. Returns the number of characters actually written if the current buf is sufficient, and returns the number of characters that will be written if not enough. In other words, the return value is the number of characters passed in.
Summarize:
1.SNPRINTF is simpler to use than strncpy.
2.snprintf can get the number of bytes copied.
3. Both have performance problems. If SRC is much larger than dest, use strncpy if dest is much larger than SRC, with snprintf.