From c043388bad5deabd35b271bec3969a37cad936ce Mon Sep 17 00:00:00 2001 From: Brian Barto Date: Mon, 2 May 2016 13:56:35 -0400 Subject: [PATCH] Incorporated geometric size expansion for input array to reduce the amount of memory reallocations. modified: src/main.c --- src/main.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/main.c b/src/main.c index f472021..77dfc8d 100644 --- a/src/main.c +++ b/src/main.c @@ -4,10 +4,11 @@ #include #include "nms.h" -#define VERSION "0.1.0" +#define VERSION "0.1.0" +#define INPUT_GROWTH_FACTOR 2 int main(int argc, char *argv[]) { - int c, o, inSize = 0; + int c, o, inSize = 0, inCapacity = 0; char *input = NULL; NmsArgs args = INIT_NMSARGS; @@ -32,7 +33,10 @@ int main(int argc, char *argv[]) { // Geting input while ((c = getchar()) != EOF) { ++inSize; - input = realloc(input, inSize + 1); + if (inSize > inCapacity) { + inCapacity = inCapacity == 0 ? INPUT_GROWTH_FACTOR : inCapacity * INPUT_GROWTH_FACTOR; + input = realloc(input, inCapacity + 1); + } input[inSize - 1] = c; input[inSize] = '\0'; }