From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from joooj.vinc17.net (joooj.vinc17.net [IPv6:2001:4b99:1:3:216:3eff:fe20:ac98]) by sourceware.org (Postfix) with ESMTPS id 99C773858C53 for ; Sun, 19 Mar 2023 23:07:23 +0000 (GMT) DMARC-Filter: OpenDMARC Filter v1.4.2 sourceware.org 99C773858C53 Authentication-Results: sourceware.org; dmarc=none (p=none dis=none) header.from=vinc17.net Authentication-Results: sourceware.org; spf=none smtp.mailfrom=vinc17.net Received: from smtp-zira.vinc17.net (128.119.75.86.rev.sfr.net [86.75.119.128]) by joooj.vinc17.net (Postfix) with ESMTPSA id D23A7C0; Mon, 20 Mar 2023 00:07:22 +0100 (CET) Received: by zira.vinc17.org (Postfix, from userid 1000) id 9B4A62800238; Mon, 20 Mar 2023 00:07:22 +0100 (CET) Date: Mon, 20 Mar 2023 00:07:22 +0100 From: Vincent Lefevre To: libc-alpha@sourceware.org Subject: Re: UB status of snprintf on invalid ptr+size combination? Message-ID: <20230319230722.GD390223@zira.vinc17.org> Mail-Followup-To: Vincent Lefevre , libc-alpha@sourceware.org References: <9d7ca3d8-6998-e741-b669-03ef42bc99f1@gmail.com> MIME-Version: 1.0 Content-Type: text/plain; charset=iso-8859-1 Content-Disposition: inline Content-Transfer-Encoding: 8bit In-Reply-To: <9d7ca3d8-6998-e741-b669-03ef42bc99f1@gmail.com> X-Mailer-Info: https://www.vinc17.net/mutt/ User-Agent: Mutt/2.2.9+71 (caea3018) vl-149028 (2023-03-14) X-Spam-Status: No, score=-1.5 required=5.0 tests=BAYES_00,KAM_DMARC_STATUS,KAM_LAZY_DOMAIN_SECURITY,SPF_HELO_NONE,SPF_NONE,TXREP autolearn=no autolearn_force=no version=3.4.6 X-Spam-Checker-Version: SpamAssassin 3.4.6 (2021-04-09) on server2.sourceware.org List-Id: On 2023-03-19 10:45:59 -0400, manfred via Libc-alpha wrote: > All of that said, back to the OP case I would not pass INT_MAX to snprintf. > If I have a situation wherein I know that the buffer is large enough, but I > don't know its exact size, I'd use sprintf and be done with it. (I'm sure > that the actual code is more elaborate than this, but still) In simple code, probably. But in actual code, it may be more natural to use snprintf. Something like that: snprintf(buf, checked ? SIZE_MAX : n, "%s", s); The function may not know the buffer size if `checked` is true, so that it uses a known bound. Thanks to common code factorized, this is more readable than if (checked) sprintf (buf, "%s", s); else snprintf(buf, n, "%s", s); in particular in the cases where the format string is complex. -- Vincent Lefèvre - Web: 100% accessible validated (X)HTML - Blog: Work: CR INRIA - computer arithmetic / AriC project (LIP, ENS-Lyon)