From 5de3be1bee65bf6df1336eaee5979afadd54a937 Mon Sep 17 00:00:00 2001 From: "Yukihiro \"Matz\" Matsumoto" Date: Wed, 2 Aug 2023 19:23:48 +0900 Subject: [PATCH] mruby-dir/dir.c (mrb_di_getwd): reduce buffer allocation size Instead of allocating `MAXPATHLEN` buffer string at the beginning, allocate smaller (64 bytes) buffer, then resize it if needed. The allocating max size is safe but consumes more memory. --- mrbgems/mruby-dir/src/dir.c | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/mrbgems/mruby-dir/src/dir.c b/mrbgems/mruby-dir/src/dir.c index 80f70df19..52d100f2b 100644 --- a/mrbgems/mruby-dir/src/dir.c +++ b/mrbgems/mruby-dir/src/dir.c @@ -34,6 +34,7 @@ #include #include #include +#include #define E_IO_ERROR mrb_exc_get_id(mrb, MRB_SYM(IOError)) @@ -128,10 +129,16 @@ static mrb_value mrb_dir_getwd(mrb_state *mrb, mrb_value klass) { mrb_value path; + mrb_int size = 64; - path = mrb_str_buf_new(mrb, MAXPATHLEN); - if (getcwd(RSTRING_PTR(path), MAXPATHLEN) == NULL) { - mrb_sys_fail(mrb, "getcwd(2)"); + path = mrb_str_buf_new(mrb, size); + while (getcwd(RSTRING_PTR(path), size) == NULL) { + int e = errno; + if (e != ERANGE) { + mrb_sys_fail(mrb, "getcwd(2)"); + } + size *= 2; + mrb_str_resize(mrb, path, size); } mrb_str_resize(mrb, path, strlen(RSTRING_PTR(path))); return path;