News for hackers. Stuff that matters.
Re:C Strings and my slow descent to madness by Night_Thastus on Thursday April 06, 2023 @11:05AM (#35469298)
It's important to mention that strncpy (and also strncpy_s) are really not a strcpy replacement, it's not intended for the same usages. The name is a total misnomer. Do not use strncpy that way!

In any case, strcpy_s (which is a good replacement for strcpy) is part of the C11 standard. I'm confused how that isn't considered portable.

Re:C Strings and my slow descent to madness by zabzonk on Thursday April 06, 2023 @11:24AM (#35469627)
it's an _optional_ part of the standard, and so can't be relied on. also, the idea behind it is pretty poor.
Re:C Strings and my slow descent to madness by Night_Thastus on Thursday April 06, 2023 @12:19PM (#35470596)
Don't both GCC, Clang and MSVC provide it? It may be optional in practice but if the major compilers support it, it's not really an issue.

The idea may not be perfect, but for C which is intended to be low overhead, strcpy_s is about as good as it gets. If you want something more user friendly, that is what C++ is for with std::string, or library implementations like Boost or QT string.

Re:C Strings and my slow descent to madness by zabzonk on Thursday April 06, 2023 @05:28PM (#35474746)
MSVC supports it, as it is an MS invention, designed by some intern, i guess. other compilers may or may not, by switches/#defines. it is worthless in any case.
Re:C Strings and my slow descent to madness by Night_Thastus on Thursday April 06, 2023 @10:18PM (#35477234)
>as it is an MS invention

Source, and why does it matter who made it?

>designed by some intern

You don't know that, nor is that how standards work.

>other compilers may or may not

So you've said basically nothing.

>it is worthless in any case.

It offers a low-overhead, safer alternative to strcpy. Is it perfect? No. But it's one of the better C options for those limited to the standard library.

Re:C Strings and my slow descent to madness by zabzonk on Friday April 07, 2023 @05:17AM (#35479763)
it was put forward to the standards comittee by MS, who have a powerful voice there. no-one else wanted it, which is why it ended up in an annex of the standard. it is badly designed, and does nothing that you can't do yourself, and should be doing yourself, in any well-written code.
Re:C Strings and my slow descent to madness by cellularmitosis on Friday April 07, 2023 @11:41AM (#35482817)
Yeah, I was a little confused by the strncpy "gotcha": "The answer is that the destination gets filled with all the characters of the source string with no room left for the null terminator."

Well, I mean, the docs specifically call that out: "If src is less than len characters long, the remainder of dst is filled with ‘\0’ characters. Otherwise, dst is not terminated."

So if you want null termination in all cases, you need to pass len-1, not len.