Recommended C string functions
Recently, I did some cleanup to nvi2's string operations. Here are some notes.
First, we need a definition to the "C string". This is very important since some libc functions do not really work with the C strings. A C string is a NUL-terminated byte sequence[1]. Further more, a function which works with the C strings must always terminate its result with '\0'. Otherwise, the function is regarded to work with the "fixed width strings"[2], or, raw memory.
strncpy(3) has been criticized a lot for the inconsistency between its name and its behavior. Sometimes, it terminates its result; but if the supplied buffer is not big enough, strncpy will just fill the buffer, and wish it can simplify the succeeding truncation handling. However, since the behavior itself is "politically wrong", this API is error-prone.
The problem is caused by the length argument. If it is the length of the string, in such a case, memcpy(3) makes more sense and gives more efficiency. If the argument is the size of the buffer, since you probably not be able to resize the buffer, the buffer must be NUL-terminated. In such a case, strlcpy(3) should be used instead.
The similar problem also happens to strncat(3), and there is also a strlcat(3). But wait... When the last time you use str*cat? If you do want the performance, memcpy is still the best choice; and if you want a clean logic, you can always use snprintf(3), or my favorite asprintf(3) if you are not tied to an existing buffer.
Don't be fear of the dynamic allocation, which may be the only approach if you have to handle an input with an unlimited length, like, a very long line. getline(3) perfectly replaces fgets(3) here. getline(3) manages a reusable dynamically allocated buffer, so that you only need to free(3) it once after you've finished reading all the lines. Ah, yes, the GNU readline(3) should be criticized here -- you have to call free(3) for each line you read -- time to switch to the BSD editline(3) API.
Links:
[1] Nul-terminated string. https://en.wikipedia.org/wiki/Null-terminated_string
[2] A stackoverflow answer. http://stackoverflow.com/a/2115015/687505











