5 ms·
Starting in C99, you can do this: snprintf(buffer, size, "%s", source); This can be put into a #define macro or inline function. If what you want is a null
by kazinator 11y ago
Starting in C99, you can do this:
snprintf(buffer, size, "%s", source);
This can be put into a #define macro or inline function.
If what you want is a null terminated, truncated copy that fits into a given buffer size, and snprintf is available, you are mad to still use strncpy.
Also, strncpy pads the destination with nulls, if there is remaining space. Because of this, the evident purpose of strncpy is to fill fixed-width text fields in "old school" fixed-field database records. Writing the extra nulls is wasteful if the data type in question is nothing but a C string.
- jedbrown 11y agoWith fixed-width records, writing the extra nulls may be important for data privacy reasons and in any case, it allows comparison using memcpy(3), diff(1), and checksums.
- _kst_ 11y agoSure, but then you have to make sure that you always maintain the extra nulls. diff(1) doesn't seem relevant; it operates on text files, which normally don't contain any null characters.
- maxlybbert 11y agoThe article also suggests using strncat for this: dest[0] = '\0'; strncat(dest, src, size);.
- angry_octet 11y agoI think we can agree that strncpy is not perfect. Perhaps we can rank by levels of sanity? my_string_cpy() < strcpy < strncpy < strncat < snprintf < strlcat I dislike the strncat approach because if the prior null termination gets lost then problems ensue, whereas with snprintf that won't happen. The BSD man page mentions that snprintf may not be safe for use in signal handlers on some systems; obviously snprintf is a much bigger piece of code. Personally I dislike using extensive macros, but I'll leave that for the flame war.