From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org Received: from vger.kernel.org (vger.kernel.org [23.128.96.18]) by smtp.lore.kernel.org (Postfix) with ESMTP id 9CC48C433EF for ; Mon, 21 Mar 2022 08:51:22 +0000 (UTC) Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand id S1345481AbiCUIwp (ORCPT ); Mon, 21 Mar 2022 04:52:45 -0400 Received: from lindbergh.monkeyblade.net ([23.128.96.19]:57788 "EHLO lindbergh.monkeyblade.net" rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP id S240765AbiCUIwm (ORCPT ); Mon, 21 Mar 2022 04:52:42 -0400 Received: from 1wt.eu (wtarreau.pck.nerim.net [62.212.114.60]) by lindbergh.monkeyblade.net (Postfix) with ESMTP id 78D647891F for ; Mon, 21 Mar 2022 01:51:16 -0700 (PDT) Received: (from willy@localhost) by pcw.home.local (8.15.2/8.15.2/Submit) id 22L8p0aG005720; Mon, 21 Mar 2022 09:51:00 +0100 Date: Mon, 21 Mar 2022 09:51:00 +0100 From: Willy Tarreau To: Alviro Iskandar Setiawan Cc: Ammar Faizi , "Paul E. McKenney" , Nugraha , Linux Kernel Mailing List , GNU/Weeb Mailing List Subject: Re: [RFC PATCH v1 6/6] tools/include/string: Implement `strdup()` and `strndup()` Message-ID: <20220321085100.GB5676@1wt.eu> References: <20220320093750.159991-1-ammarfaizi2@gnuweeb.org> <20220320093750.159991-7-ammarfaizi2@gnuweeb.org> <20220321075308.GD29580@1wt.eu> MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: User-Agent: Mutt/1.10.1 (2018-07-13) Precedence: bulk List-ID: X-Mailing-List: linux-kernel@vger.kernel.org On Mon, Mar 21, 2022 at 03:16:54PM +0700, Alviro Iskandar Setiawan wrote: > On Mon, Mar 21, 2022 at 2:53 PM Willy Tarreau wrote: > > Here it can cost quite a lot for large values of maxlen. Please just use > > a variant of the proposal above like this one: > > > > size_t len; > > char *ret; > > > > len = strlen(str); > > if (len > maxlen) > > len = maxlen; > > ret = malloc(len + 1); > > if (ret) > > memcpy(ret, str, len); > > return ret; > > Maybe better to use strnlen(), see the detail at man 3 strnlen. > > size_t strnlen(const char *s, size_t maxlen); > > The strnlen() function returns the number of bytes in the string > pointed to by s, excluding the terminating null byte ('\0'), but at > most maxlen. In doing this, strnlen() looks only at the first maxlen > characters in the string pointed to by s and never beyond s[maxlen-1]. > > Should be trivial to add strnlen() with a separate patch before this patch. > > So it can be: > > size_t len; > char *ret; > > len = strnlen(str, maxlen); > ret = malloc(len + 1); > if (__builtin_expect(ret != NULL, 1)) { > memcpy(ret, str, len); > ret[len] = '\0'; > } > return ret; > > Thoughts? I thought about it as well and while I was seeking the simplest route, I agree it would indeed be cleaner. Willy