53 points · by ohjeez · 8y ago · 78 comments
If the standard libs are that bad, the community should really lobby for the inclusion of a "safe" string copy into the C standard. Failing that, use a battle-tested third-party library like bstrlib[0].
If you must write C, you should use a real string library, and not string.h.
I agree that a standard fix for this would be great. It's been five years since I wrote the post, the solution has been available for many years longer than that, and the standards committee has shown no interest in fixing this issue. In the interim I think it would be irresponsible for developers to continue using strncpy or any of the other unsafe options when strcpy_safe is so simple and effective.
Also, it doesn't appear to be specified what happens if the count argument is too large to be represented as a ssize_t. The destination buffer would have to be extremely large, so it probably doesn't happen in practice, but it'd be good to specify it, or at least explicitly state it's unspecified / undefined.
https://www.kernel.org/doc/htmldocs/kernel-api/API-strscpy.h...
But this year I decided to make them safe instead. In this case the spec is broken.
"C strings and string functions aren't designed to be safe. If you want safe strings use a library."
Let's not forget that it's also not natively available in glibc. Though you'll find it in every BSD you can think of.
Like snprintf(3), the strlcpy() and strlcat() functions return the total
length of the string they tried to create. For strlcpy() that means the
length of src. For strlcat() that means the initial length of dst plus
the length of src.
So if you've mmaped in something like the OpenStreetMaps xml dump file and try to strlcpy out the first 100 bytes (because you didn't want to have to null terminate it yourself after a memcpy), you'll notice that your program is running rather slowly.In fairness, that is probably just not the target "market" for strlcpy. Presumably, it is meant for "please copy this whole string which I expect to fit in the target (but catch me in the rare case that it does not)".
If efficiency is not a concern for you and you rather like the convenience, good for you.
Personally I feel plain const char pointers (plus length, depending on expected size) are good enough to emulate the immutable string type. For modifiable strings, I still prefer viewing them as chunks of memory, using char pointer + length + capacity. Nice thing is, you can easily go from the former to the latter in the lifetime of any one string. You can also pool many strings in large chunks if you build only one string at any one time.
Micro-optimizing each line of C code based on gut feeling is not an option if quality matters.
If you have the length of both, simply assert the length of the destination is <= the length of the source. Problem solved (bugs become obvious in testing).
Asserts are necessary, but not sufficient.
If the destination buffer doesn't have a fixed length then it will fail to compile.
This is similar to your suggestion with these improvements: - Template deduction of the destination size is done - this is essential to avoid bugs - Detection of overwrites is done in release builds as well as during testing - Detection of overwrites is automatic - it doesn't require manually adding asserts to call sites - strcpy_s exists in some standard libraries
I do have some maintainability concerns though about the promulgation of numerous competing home-brew solutions to a near trivial problem throughout a code base.
With `strncpy`, the caller assumes the responsibility of buffer size (by specify that size explicitly every single time. I thought that responsibility is not being debated within the current context.
I bring it up because the article makes programming errors on the part of the caller part of the case for its "safe" solution.
TL;DR - I've reviewed enough code to know that software developers pass the wrong size to strncpy and friends.
Really, stop using C. To quote Hayao Miyazaki, C was a mistake.
#define BUFSIZE 100
char buf[BUFSIZE+1]
buf[BUFSIZE]=0 // for global var, it is already zeroed, right?
Then one can call strncpy(buf, BUFSIZE, ...) without worrying about null-termination.How does this work if the size of the destination isn't known at compile time? I.e., it's not "buffer[5]”?
And this is progress. I have fixed code that looked something like this:
strncpy(dst, sizeof(dst), src);
data[sizeof(dst)-1] = 0;
See the bug? Of course not, because it's not visible, but I've seen this pattern used where dst is a pointer. This means that four or eight bytes (three or seven if you don't count the null terminator) gets copied, regardless of how many bytes dst points to. With strcpy_safe an attempt to copy to dst would not work and the developer would have to fix their code.Every mistake that can be made, will be made.
> The focus of this post is on fixed-size string buffers, but the technique applies to any type of fixed-length buffer.
I'm a big fan of using strategies to avoid bugs. Another strategy than can be a big help is to spend a little time thinking about what kinds of strings you are going to be using and how big they might be. And then sanitizing your program input based on those sizes. Find the too-long strings before they get into your program and before you start copying them around.
The system I'm responsible for came into being as a set of programs on a Univac II and was a bunch of C and FORTRAN when I joined. Because of the need to pass data between C and FORTRAN programs/code, we had a set of 10-20 standard string sizes, based on what kind of text you had. We no longer write new code in either C or FORTRAN, but maintain the concept of standard sizes for our text. By specifying the kind of text (we also do this with numbers) in the design steps, we save far more time and effort than we spend over the entire SDLC.