this improves the realloc loop. there is no need to constantly call realloc to
resize the memory. if we have enough, we have enough. also no need to penny
pinch the initial allocation.

calling sysctl all the time is still wasteful, but harder to fix.

Index: machine.c
===================================================================
RCS file: /cvs/src/usr.bin/top/machine.c,v
retrieving revision 1.86
diff -u -p -r1.86 machine.c
--- machine.c   11 May 2016 08:11:27 -0000      1.86
+++ machine.c   11 May 2016 17:42:42 -0000
@@ -366,20 +366,25 @@ static char **
 get_proc_args(struct kinfo_proc *kp)
 {
        static char     **s;
-       size_t          siz = 100;
+       static size_t   siz = 1023;
        int             mib[4];
 
-       for (;; siz *= 2) {
-               if ((s = realloc(s, siz)) == NULL)
-                       err(1, NULL);
-               mib[0] = CTL_KERN;
-               mib[1] = KERN_PROC_ARGS;
-               mib[2] = kp->p_pid;
-               mib[3] = KERN_PROC_ARGV;
-               if (sysctl(mib, 4, s, &siz, NULL, 0) == 0)
+       if (!s && !(s = malloc(siz)))
+               err(1, NULL);
+
+       mib[0] = CTL_KERN;
+       mib[1] = KERN_PROC_ARGS;
+       mib[2] = kp->p_pid;
+       mib[3] = KERN_PROC_ARGV;
+       for (;;) {
+               size_t space = siz;
+               if (sysctl(mib, 4, s, &space, NULL, 0) == 0)
                        break;
                if (errno != ENOMEM)
                        return NULL;
+               siz *= 2;
+               if ((s = realloc(s, siz)) == NULL)
+                       err(1, NULL);
        }
        return s;
 }

Reply via email to