Skip to content

Commit

Permalink
Improve argv_to_string_alloc()
Browse files Browse the repository at this point in the history
1. Fix bug in argv_to_string_alloc(),
   which did not increase buffer size to account for number of separators.

2. Improve coding
   a. Initialize buffer size to one to account for terminator,
      which avoids the need to later increment by one.
   b. Call concat_argv() directly, instead of calling argv_to_string(),
      which is a wrapper.

3. Add similar function argv_to_string_alloc_prefix(),
   which preloads string buffer with a prefix string.
  • Loading branch information
stevenyvr987 committed May 17, 2019
1 parent 6afbd89 commit 557b020
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
1 change: 1 addition & 0 deletions include/tig/argv.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
#define DIFF_ARGS "%(diffargs)"

bool argv_to_string(const char *argv[], char *buf, size_t buflen, const char *sep);
char *argv_to_string_alloc_prefix(const char *argv[], const char *sep, const char *prefix);
char *argv_to_string_alloc(const char *argv[], const char *sep);
bool argv_to_string_quoted(const char *argv[SIZEOF_ARG], char *buf, size_t buflen, const char *sep);
bool argv_from_string_no_quotes(const char *argv[SIZEOF_ARG], int *argc, char *cmd);
Expand Down
37 changes: 32 additions & 5 deletions src/argv.c
Original file line number Diff line number Diff line change
Expand Up @@ -56,16 +56,43 @@ concat_argv(const char *argv[], char *buf, size_t buflen, const char *sep, bool
}

char *
argv_to_string_alloc(const char *argv[], const char *sep)
argv_to_string_alloc_prefix(const char *argv[], const char *sep, const char *prefix)
{
size_t i, size = 0;
char *buf;
size_t i, size = 1;
for (i = 0; argv[i]; i++)
size += strlen(argv[i]);

/* Increase buffer size by separator size and number of separators */
if (sep) if (i) size += strlen(sep) * (i - 1);

/* Increase buffer size by prefix size */
if (prefix) size += strlen(prefix);

char *buf = malloc(size);
if (buf) {

/* Preload buffer with prefix */
for (i = 0; prefix[i]; i++) buf[i] = prefix[i];

/* Load buffer after prefix with concatenated version of argv */
if (concat_argv(argv, buf + i, size, sep, false)) return buf;
}
free(buf);
return NULL;
}

char *
argv_to_string_alloc(const char *argv[], const char *sep)
{
size_t i, size = 1;
for (i = 0; argv[i]; i++)
size += strlen(argv[i]);

buf = malloc(size + 1);
if (buf && argv_to_string(argv, buf, size + 1, sep))
/* Increase buffer size by separator size and number of separators */
if (sep) if (i) size += strlen(sep) * (i - 1);

char *buf = malloc(size);
if (buf && concat_argv(argv, buf, size, sep, false))
return buf;
free(buf);
return NULL;
Expand Down

0 comments on commit 557b020

Please sign in to comment.