This is the mail archive of the libc-alpha@sourceware.org mailing list for the glibc project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Implement C11 annex K?


Russ Allbery wrote:
how would you recommend writing this
function without using strlcpy and strlcat?

char *
vector_join(const struct vector *vector, const char *seperator)
{
     char *string;
     size_t i, size, seplen;

     /* If the vector is empty, this is trivial. */
     assert(vector != NULL);
     if (vector->count == 0)
         return xstrdup("");

     /* Determine the total size of the resulting string. */
     seplen = strlen(seperator);
     for (size = 0, i = 0; i < vector->count; i++)
         size += strlen(vector->strings[i]);
     size += (vector->count - 1) * seplen + 1;

     /* Allocate the memory and build up the string using strlcat. */
     string = xmalloc(size);
     strlcpy(string, vector->strings[0], size);
     for (i = 1; i < vector->count; i++) {
         strlcat(string, seperator, size);
         strlcat(string, vector->strings[i], size);
     }
     return string;
}

The following is certainly shorter and to my eyes considerably easier to follow, which appears to be the goal here (not efficiency, obviously, or we wouldn't be talking about strlcat).

 char *
 vector_join(const struct vector *vector, const char *sep)
 {
   char *string = xstrdup("");
   for (size_t i = 0; i < vector->count; i++) {
char *t = xasprintf("%s%s%s", string, i ? sep : "", vector->strings[i]);
     free (string);
     string = t;
   }
   return string;
 }


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]