xrealloc_getcwd_or_warn: smaller cod and less wasted RAM at run time
authorDenis Vlasenko <vda.linux@googlemail.com>
Sat, 29 Sep 2007 19:19:55 +0000 (19:19 -0000)
committerDenis Vlasenko <vda.linux@googlemail.com>
Sat, 29 Sep 2007 19:19:55 +0000 (19:19 -0000)
libbb/xgetcwd.c

index ec1d8f7a4231669a6bff3534c311a28444d600b4..c194e23037513e233780033464566bb5f99c297f 100644 (file)
@@ -9,9 +9,6 @@
 
 #include "libbb.h"
 
-/* Amount to increase buffer size by in each try. */
-#define PATH_INCR 32
-
 /* Return the current directory, newly allocated, arbitrarily long.
    Return NULL and set errno on error.
    If argument is not NULL (previous usage allocate memory), call free()
 char *
 xrealloc_getcwd_or_warn(char *cwd)
 {
+#define PATH_INCR 64
+
        char *ret;
        unsigned path_max;
 
-       path_max = (unsigned) PATH_MAX;
-       path_max += 2;                /* The getcwd docs say to do this. */
-
-       if (cwd == NULL)
-               cwd = xmalloc(path_max);
+       path_max = 128; /* 128 + 64 should be enough for 99% of cases */
 
-       while ((ret = getcwd(cwd, path_max)) == NULL && errno == ERANGE) {
+       while (1) {
                path_max += PATH_INCR;
                cwd = xrealloc(cwd, path_max);
+               ret = getcwd(cwd, path_max);
+               if (ret == NULL) {
+                       if (errno == ERANGE)
+                               continue;
+                       free(cwd);
+                       bb_perror_msg("getcwd");
+                       return NULL;
+               }
+               cwd = xrealloc(cwd, strlen(cwd) + 1);
+               return cwd;
        }
-
-       if (ret == NULL) {
-               free(cwd);
-               bb_perror_msg("getcwd");
-               return NULL;
-       }
-
-       return cwd;
 }