bug-gnulib
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: string types


From: Bruno Haible
Subject: Re: string types
Date: Tue, 31 Dec 2019 10:53:59 +0100
User-agent: KMail/5.1.3 (Linux/4.4.0-170-generic; KDE/5.18.0; x86_64; ; )

Hi Tim,

> >   - providing primitives for string allocation reduces the amount of buffer
> >     overflow bugs that otherwise occur in this area. [1]
> > [1] https://lists.gnu.org/archive/html/bug-gnulib/2019-09/msg00031.html

> here is a string concatenation function without ellipsis, analogue to
> writev() and struct iovec - just a suggestion. Instead of 'struct
> strvec' a new string_t type would be handy.
> 
> #include <stddef.h>
> #include <stdio.h>
> #include <stdlib.h>
> #include <string.h>
> 
> struct strvec {
>   char *strv_base;
>   size_t strv_len;
> };
> 
> __attribute__ ((nonnull (1)))
> char *concat_stringv(const struct strvec *strv)
> {
>   const struct strvec *str;
>   size_t len = 0;
>   char *buf;
> 
>   for (str = strv; str->strv_base; str++)
>     len += str->strv_len;
> 
>   if (!(buf = malloc(len + 1)))
>     return buf;
> 
>   len = 0;
>   for (str = strv; str->strv_base; len += str->strv_len, str++)
>     memcpy(buf + len, str->strv_base, str->strv_len);
> 
>   buf[len] = 0;
> 
>   return buf;
> }
> 
> void main(void)
> {
>   char *s = concat_stringv((struct strvec []) {
>     { "a", 1 },
>     { "b", 1 },
>     { NULL }
>   });

This looks good. It brings us one step closer to the stated goal [1].

Would you like to contribute such a 'string-alloc' module that, together with
'strdup' and 'asprintf', removes most needs to create a string's contents
"by hand"?

Regarding the type name: There can't be a 'string_t' in C, I would say,
because you will always have the NUL-terminated strings on one side and what
you call a 'wget_string' on the other side, and there can't be a clear winner
between both.

Bruno




reply via email to

[Prev in Thread] Current Thread [Next in Thread]