2022-03-21 13:58:57

by Alviro Iskandar Setiawan

[permalink] [raw]
Subject: Re: [RFC PATCH v1 6/6] tools/include/string: Implement `strdup()` and `strndup()`

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?

-- Viro


2022-03-21 22:58:06

by Willy Tarreau

[permalink] [raw]
Subject: Re: [RFC PATCH v1 6/6] tools/include/string: Implement `strdup()` and `strndup()`

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