Make rpmExpand() smarter wrt memory allocations
authorPanu Matilainen <pmatilai@redhat.com>
Wed, 16 Jul 2008 07:52:33 +0000 (10:52 +0300)
committerPanu Matilainen <pmatilai@redhat.com>
Wed, 16 Jul 2008 07:52:33 +0000 (10:52 +0300)
- precalculate unexpanded size and allocate enough for that plus MACROBUFSIZ
  for expansion
- typical allocation is way smaller than what gets allocated "just in case",
  calculate expanded size and realloc to actual size to avoid wasting
  memory

rpmio/macro.c

index 198056f..ad1f94a 100644 (file)
@@ -1583,15 +1583,26 @@ rpmExpand(const char *arg, ...)
        goto exit;
     }
 
-    buf = xmalloc(blen);
+    /* precalculate unexpanded size on top of MACROBUFSIZ */
+    va_start(ap, arg);
+    for (s = arg; s != NULL; s = va_arg(ap, const char *))
+       blen += strlen(s);
+    va_end(ap);
+
+    buf = xmalloc(blen + 1);
     buf[0] = '\0';
 
     va_start(ap, arg);
     for (pe = buf, s = arg; s != NULL; s = va_arg(ap, const char *))
        pe = stpcpy(pe, s);
     va_end(ap);
+
     (void) expandMacros(NULL, NULL, buf, blen);
 
+    /* expanded output is usually much less than alloced buffer, downsize */
+    blen = strlen(buf);
+    buf = xrealloc(buf, blen + 1);
+
 exit:
     return buf;
 }