time concatenates its arguments to pass it to run_command in a
suboptimal manner: The destination string is traversed from the
beginning on every iteration due to strcat and we have a left-over
separator at the end, while it's only needed in-between.

In preparation for factoring the code out as a library strjoin function,
fix these shortcomings.

Signed-off-by: Ahmad Fatoum <a.fat...@pengutronix.de>
---
v1 -> v2:
  - swapped order with follow-up commit (Sascha)
---
 commands/time.c | 12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)

diff --git a/commands/time.c b/commands/time.c
index 72647a3bb876..0a38db61845d 100644
--- a/commands/time.c
+++ b/commands/time.c
@@ -10,7 +10,7 @@
 static int do_time(int argc, char *argv[])
 {
        int i, opt;
-       unsigned char *buf;
+       unsigned char *buf, *p;
        u64 start, end, diff64;
        bool nanoseconds = false;
        int len = 1; /* '\0' */
@@ -34,13 +34,15 @@ static int do_time(int argc, char *argv[])
        for (i = 0; i < argc; i++)
                len += strlen(argv[i]) + 1;
 
-       buf = xzalloc(len);
+       p = buf = xmalloc(len);
 
-       for (i = 0; i < argc; i++) {
-               strcat(buf, argv[i]);
-               strcat(buf, " ");
+       for (i = 0; i < argc - 1; i++) {
+               p = stpcpy(p, argv[i]);
+               p = mempcpy(p, " ", strlen(" "));
        }
 
+       stpcpy(p, argv[i]);
+
        start = get_time_ns();
 
        run_command(buf);
-- 
2.39.2


Reply via email to