Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

This. I don't understand the objection and I spent 20 years writing C code. The reason to use strlcpy is not to _fix the bug_ but rather _to prevent the bug from turning into a crash, memory corruption, or exploit_. It also forces discipline by carrying around the length. As you say, it's also a drop-in.

A truncation bug is a hell of a lot easier to debug than memory corruption.



I've worked on embedded RTOS projects where we had our own strlcpy implementation - it's fine. Well, I mean, all the str functions suck because C strings, but that's exactly why sticking to a good shared set of idioms and staying organized is so important. And in C, that means manually tagging buffers with their length, no getting around that. Given that, strlcpy is less bug-prone than strncpy, simply due to requiring less lines of code to use correctly per invocation.

I think a lot of the confusion in the C string discourse comes from people thinking they should rely on the NULL termination byte for string length. You really shouldn't, and if you have to do it, you need to be extra careful to check all your assertions that it will be properly terminated. Just carry around the length, and bundle it with the pointer in a struct to pass it around when it makes sense. Not the most ergonomic, but it's C, what can ya do.


It's pretty funny that C strings were decided to be NULL terminated in the ancient past for 'convenience', but it turns out you still need to carry the length around anyway.


Not to defend C strings too hard, but it does make some sort of sense, IMO. You have to manage all your buffers manually in C, whether they contain a string or not. If you store a string of length 5 in a 10-byte buffer, you still need to manage the 10-byte buffer. Raw pointers kept things very flexible and lightweight when C was created.

Nowadays, things like C++ string_view's and Rust str slices handle this for you automatically, but those came around much later and require more sophistication at compile time.


Yes, but it's not that much more sophistication, because C already supports structs. (Though I'm not sure if the first versions of C already had structs?)


> It also forces discipline by carrying around the length.

LOL. It does not force anything - you can mishandle source or destination buffer lengths very easily and compiler won't say anything.

I sometimes wonder what kind of disaster will have to happen to make C programmers agree on a standard buffer (i.e. pointer+size) type with mandatory runtime bounds enforcement ....


Force is too strong a word. Yes, it's possible someone just passes whatever, or just passes strlen(s) which is an even dumber answer.




Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: