git/list[1] front-page[2] threads[3] people[4] search[5] about
 

Re: [PATCH] Make xstrndup common

From
Alex Riesen <raa.lkml@gmail.com>
Date
May 3, 2007, 09:06 UTC
Message-ID
<81b0412b0705030206u3a6b8a46qfd98ccf597d3c96e@mail.gmail.com>
In-Reply-To
<Pine.LNX.4.64.0705022248040.28708@iabervon.org>
On 5/3/07, Daniel Barkalow <barkalow@iabervon.org> wrote:
Show 11 quoted lines
> +static inline char *xstrndup(const char *str, int len)
> +{
> +       char *ret;
> +       int i;
> +       for (i = 0; i < len && str[i]; i++)
> +               ;
> +       ret = xmalloc(i + 1);
> +       strncpy(ret, str, i);
> +       ret[i] = '\0';
> +       return ret;
> +}
I'd suggest using platform-optimized memchr:
static inline char *xstrndup(const char *s, int len)
{
    char *p = memchr(s, 0, len);
    int n = p ? p - s: len;
    p = xmalloc(n + 1);
    memcpy(p, s, n);
    p[n] = '\0';
    return p;
}
Previous: Junio C HamanoNext: Junio C Hamano
Message 5 of 6 in “Make xstrndup common”
  1. Make xstrndup commonDaniel Barkalow, May 3, 2007
  2. Junio C HamanoMay 3, 2007
  3. Daniel BarkalowMay 3, 2007
  4. Junio C HamanoMay 3, 2007
  5. Alex RiesenMay 3, 2007
  6. Junio C HamanoMay 4, 2007

Read the whole thread, see it on lore, or plain text.

$ cat FOOTERMessages come from the public archive at lore.kernel.org/git, fetched every hour. The front page is chosen and written each morning by an AI editor and can be wrong; the threads themselves are the record. About and API. For agents: an MCP server at https://gitlist.dev/mcp, and any thread, story or person page as Markdown by adding .md to its URL (or sending Accept: text/markdown). Details in /llms.txt.