Live data from Hacker News

Stop using strncpy already (2013)

randomascii.wordpress.com

1–10 of 83 posts

Re: Stop using strncpy already (2013)

#4
post #3

Two years after this post, the Linux kernel added strscpy, the api of which is equivalent to the safe strncpy in this post. Internally, it stops copying once it reaches the null terminator. https://lwn.net/Articles/659214/

The article's proposed implementation uses a template to guarantee that egregious mistakes will fail to compile. This is clever, but it's C++. The kernel's version isn't quite as safe because it can overrun the destination. In principle it's impossible for it to be safe, because this is C, and neither the compiler nor the programmer can tell how big the destination is. We have to rely, as the article complains, on the programmer calling the function to know how big the buffer is.

Re: Stop using strncpy already (2013)

#5
> strlcpy is designed to solve the null-termination problems – it always null-terminates. It’s certainly an improvement over strncpy, however it isn’t natively available in VC++.

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.

Re: Stop using strncpy already (2013)

#6
I feel like there are a lot of good alternatives to C. What we did on our team was get our C compiling under g++, and then refactor as C++14. Now string copies are trivial and safe. I'm sure it would have been even safer to switch to Rust or something, but no one in my company has any experience with that, while there were a few C++ gurus.

Re: Stop using strncpy already (2013)

#7
In principle, I feel like "Ignore the language-provided standard libraries and use this little macro I wrote in all your code" is bad advice.

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].

[0]http://bstring.sourceforge.net/

Re: Stop using strncpy already (2013)

#10
post #5

> strlcpy is designed to solve the null-termination problems – it always null-terminates. It’s certainly an improvement over strncpy, however it isn’t natively available in VC++. 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.

Sadly, it still has this braindamage:

  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.
Post reply on HN