json: fix off-by-one in memory alloc
authorJens Axboe <axboe@kernel.dk>
Tue, 13 Nov 2012 12:55:38 +0000 (05:55 -0700)
committerJens Axboe <axboe@kernel.dk>
Tue, 13 Nov 2012 12:55:38 +0000 (05:55 -0700)
Tighten it a bit too, checking for empty string.

Signed-off-by: Jens Axboe <axboe@kernel.dk>
json.c

diff --git a/json.c b/json.c
index ea61af7..cdc3b21 100644 (file)
--- a/json.c
+++ b/json.c
@@ -63,18 +63,22 @@ static char *strdup_escape(const char *str)
        char *p, *ret;
        int escapes;
 
+       if (!strlen(str))
+               return NULL;
+
        escapes = 0;
        while ((input = strpbrk(input, "\\\"")) != NULL) {
                escapes++;
                input++;
        }
 
-       p = ret = malloc(strlen(str) + escapes);
+       p = ret = malloc(strlen(str) + escapes + 1);
        while (*str) {
                if (*str == '\\' || *str == '\"')
                        *p++ = '\\';
                *p++ = *str++;
        }
+       *p = '\0';
 
        return ret;
 }