Path: csiph.com!news.mixmin.net!eternal-september.org!reader01.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c++ Subject: Re: Never use strncpy! Date: Wed, 21 Sep 2022 18:00:13 -0700 Organization: None to speak of Lines: 50 Message-ID: <87sfkkdy02.fsf@nosuchdomain.example.com> References: <87o7v8zc4x.fsf@bsb.me.uk> <87czboz48n.fsf@bsb.me.uk> MIME-Version: 1.0 Content-Type: text/plain Injection-Info: reader01.eternal-september.org; posting-host="b6dd3111f3087e08fb468b174c9193d6"; logging-data="2051493"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18oJSs5aGF2Udhl9IW+Bgi8" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/27.2 (gnu/linux) Cancel-Lock: sha1:4Ww1W4zMcfM+YgBr6ApIznCffO4= sha1:Im6Ll/8YPoySqRiCJ4YQ9vdDcY4= Xref: csiph.com comp.lang.c++:86479 Richard Damon writes: > On 9/21/22 7:39 PM, Ben Bacarisse wrote: >> Richard Damon writes: >> >>> On 9/21/22 4:49 PM, Ben Bacarisse wrote: >>>> Andrey Tarasevich writes: >>>> >>>>> On 9/21/2022 3:04 AM, Juha Nieminen wrote: >>>>>> I always thought that std::strncpy() works exactly like std::strcpy(), >>>>>> except that it stops early if the specified count is reached. Turns out >>>>>> that I was gravely mistaken: >>>>>> >>>>> >>>>> The matter has been explained, explained and over-explained to death >>>>> already, including here in comp.lang.* newsgroups. It is well-known >>>>> that `strncpy` has never been intended as a "safe string copying" >>>>> function. It is a niche function introduced for so called >>>>> "fixed-width" string support. >>>>> >>>>> https://stackoverflow.com/questions/2886931/difference-fixed-width-strings-and-zero-terminated-strings >>>>> >>>>> It has never been intended for use with zero-terminated strings. >>>> Except for the quibble that a null in the source string is respected -- >>>> i.e. the destination is considered to be a fixed-width field but not the >>>> source. >>> >>> Yes, it is to copy a "C String" (Null Terminated) into a fixed width >>> field. >> Again, a quibble: not quite. A null will be respected, but there is >> no need for the source to be a C string. > > It may be able to do more, but I suspect the purpose it was designed > was for that. According to the standard's description, the source clearly does not have to point to a C string -- and strncpy() would work perfectly well to copy one fixed-sized buffer to another, which is a very plausible use case if you're working with such a data structure. char source[5] = "hello"; // no null terminator char target[5]; strncpy(target, source, sizeof target); Of course it also works if the source is a pointer to a C string, and it's explicitly required to deal with the null terminator. -- Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com Working, but not speaking, for Philips void Void(void) { Void(); } /* The recursive call of the void */