]> git.ozlabs.org Git - ccan/blobdiff - ccan/opt/test/utils.c
opt: neaten tests with helpers.
[ccan] / ccan / opt / test / utils.c
index 5b054f87f315ce7524dd5c90456467c29e80e777..21e0b727ebd6cab4762526dc5a21a11a3eb5f072 100644 (file)
@@ -1,4 +1,4 @@
-#define _GNU_SOURCE
+#include "config.h"
 #include <ccan/tap/tap.h>
 #include <stdarg.h>
 #include <stdlib.h>
@@ -29,13 +29,15 @@ void show_arg(char buf[OPT_SHOW_LEN], const char *arg)
 
 char *err_output = NULL;
 
-static void save_err_output(const char *fmt, ...)
+void save_err_output(const char *fmt, ...)
 {
        va_list ap;
        char *p;
 
        va_start(ap, fmt);
-       vasprintf(&p, fmt, ap);
+       /* Check return, for fascist gcc */
+       if (vasprintf(&p, fmt, ap) == -1)
+               p = NULL;
        va_end(ap);
 
        if (err_output) {
@@ -47,7 +49,15 @@ static void save_err_output(const char *fmt, ...)
                err_output = p;
 }      
 
-/* FIXME: This leaks, BTW. */
+void reset_options(void)
+{
+       opt_free_table();
+       free(err_output);
+       err_output = NULL;
+}
+
+static bool allocated = false;
+
 bool parse_args(int *argc, char ***argv, ...)
 {
        char **a;
@@ -61,7 +71,12 @@ bool parse_args(int *argc, char ***argv, ...)
                (*argc)++;
                a = realloc(a, sizeof(*a) * (*argc + 1));
        }
+
+       if (allocated)
+               free(*argv);
+
        *argv = a;
+       allocated = true;
        /* Re-set before parsing. */
        optind = 0;