Commit 64e109e26cc9738523d26585c3d79751be49215d

antirez 2013-02-08T12:18:42

linenoiseHistorySetMaxLen() was broken and never tested. Fixed.

diff --git a/linenoise.c b/linenoise.c
index 8f1dcff..c690477 100644
--- a/linenoise.c
+++ b/linenoise.c
@@ -829,8 +829,16 @@ int linenoiseHistorySetMaxLen(int len) {
 
         new = malloc(sizeof(char*)*len);
         if (new == NULL) return 0;
-        if (len < tocopy) tocopy = len;
-        memcpy(new,history+(history_max_len-tocopy), sizeof(char*)*tocopy);
+
+        /* If we can't copy everything, free the elements we'll not use. */
+        if (len < tocopy) {
+            int j;
+
+            for (j = 0; j < tocopy-len; j++) free(history[j]);
+            tocopy = len;
+        }
+        memset(new,0,sizeof(char*)*len);
+        memcpy(new,history+(history_len-tocopy), sizeof(char*)*tocopy);
         free(history);
         history = new;
     }