Hacker News new | ask | show | jobs
by ori_b 4283 days ago
strlcpy is designed to make it easy to detect truncation. You get back the buffer size you need to store the result. If this size is >= the size of the buffer, you truncated.
1 comments

You can just keep going, building up your string using strlcpy/strlcat as you go, and check for truncation (whether from this call, or a previous one) using the return value whenever it's convenient. Depending on what sort of programs you write, truncation might even not be a problem anywhere from some to virtually all of the time, so in those cases you can just let it happen and the code ends up even simpler.

(When I first discovered strlcpy/strlcat I went and changed a bunch of string-fiddling code to use them and it was really amazing how much simpler everything became. Virtually all of my bounds checks could go away, leaving just the string stuff. Much nicer? Well, I wouldn't go that far. But certainly fewer ways for it to go wrong.)