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

`strlcpy` is the function you probably want. but again it is not standard. https://lwn.net/Articles/507319/

I think the reason people don't want to standardise this kind of function is it often gives wrong behaviour. for example if you are trying to copy a string into a fixed buffer and its too long then often it is an error or potentially even a security bug to truncate it. so these functions generally do the 'wrong' thing even though they are 'safer'. if you are dealing with static buffers then I think you should be explicitly checking the source fits in the target and then handling the error case. you could even have a function like `strlcpy` that does `strlen` then checks if it fits, then does the copy or return an error code. alternatively, if the string should always fit and you don't want to handle the error case then the safe thing to do is check at runtime that it fits then abort the program if it doesn't fit.



On systems that aren't memory constrained, we just shouldn't be using static buffers at all. Just always use something like asprintf() and free() the result when you're done. No, it's not in the C or POSIX standards, and that's a shame, but it's at least available on Linux and the BSDs.

I end up working on a lot of code that uses Glib, so I tend to use g_strdup_printf() a lot, which works the same as asprintf().

Ultimately the cost of allocations is usually not a big deal, and you gain a lot of safety. Sure, you then have to remember to free(), but I'll take a memory leak over a segfault (and its possible security consequences) any day.

And if allocation cost is a problem, you can always go back and optimize with static buffers later. That shouldn't be the default that people reach for, though.


strlcpy is not needed, strcpy_s (not strncpy_s) is safe and is part of the C11 standard.|

In fact, strlcpy is worse:

* strlcpy truncates the source string to fit in the destination (which is a security risk)

* strlcpy does not perform all the runtime checks that strcpy_s does

* strlcpy does not make failures obvious by setting the destination to a null string or calling a handler if the call fails.


> strcpy_s is part of the C11 standard

an optional part, which makes it pretty worthless, if it were not so already.


No, it’s not. The return value it provides is generally unwanted.




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

Search: