]> git.ipfire.org Git - thirdparty/man-pages.git/commitdiff
printf.3: Simplify the example code
authorWalter Harms <wharms@bfs.de>
Sat, 11 Apr 2015 07:29:06 +0000 (09:29 +0200)
committerMichael Kerrisk <mtk.manpages@gmail.com>
Sat, 11 Apr 2015 07:34:05 +0000 (09:34 +0200)
(Minor tweaks by mtk)

Signed-off-by: Michael Kerrisk <mtk.manpages@gmail.com>
man3/printf.3

index 8c95f960601bf4b0551479cf12ab9ad80fddba9e..6a6c128c0b58c97111b1776e74fa0d63bdfaaa14 100644 (file)
@@ -1079,48 +1079,33 @@ To allocate a sufficiently large string and print into it
 char *
 make_message(const char *fmt, ...)
 {
-    int n;
-    int size = 100;     /* Guess we need no more than 100 bytes */
-    char *p, *np;
+    int size = 0;
+    char *p = NULL;
     va_list ap;
 
-    p = malloc(size);
-    if (p == NULL)
-        return NULL;
-
-    while (1) {
-
-        /* Try to print in the allocated space */
-
-        va_start(ap, fmt);
-        n = vsnprintf(p, size, fmt, ap);
-        va_end(ap);
-
-        /* Check error code */
-
-        if (n < 0) {
-            free(p);
-            return NULL;
-        }
+    /* Determine required size */
 
-        /* If that worked, return the string */
+    va_start(ap, fmt);
+    size = vsnprintf(p, size, fmt, ap);
+    va_end(ap);
 
-        if (n < size)
-            return p;
-
-        /* Else try again with more space */
-
-        size = n + 1;       /* Precisely what is needed */
+    if (size < 0)
+        return NULL;
 
+    size++;            /* For '\\0' */
+    p = malloc(size);
+    if (p == NULL)
+        return NULL;
 
-        np = realloc(p, size);
-        if (np == NULL) {
-            free(p);
-            return NULL;
-        } else {
-            p = np;
-        }
+    va_start(ap, fmt);
+    size = vsnprintf(p, size, fmt, ap);
+    if (size < 0) {
+       free(p);
+       return NULL;
     }
+    va_end(ap);
+
+    return p;
 }
 .fi
 .PP