From b0103ea45802df07affe086d1775d73b45a6e8b2 Mon Sep 17 00:00:00 2001 From: Eric Fischer Date: Wed, 5 Feb 2014 16:39:50 -0800 Subject: [PATCH] Growing string instead of static buffer --- json.c | 51 ++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 38 insertions(+), 13 deletions(-) diff --git a/json.c b/json.c index a0dfa2a..5974202 100644 --- a/json.c +++ b/json.c @@ -68,6 +68,33 @@ int peek(FILE *f) { return c; } +struct string { + char *buf; + int n; + int nalloc; +}; + +static void string_init(struct string *s) { + s->nalloc = 500; + s->buf = malloc(s->nalloc); + s->n = 0; + s->buf[0] = '\0'; +} + +static void string_append(struct string *s, char c) { + if (s->n + 2 >= s->nalloc) { + s->nalloc += 500; + s->buf = realloc(s->buf, s->nalloc); + } + + s->buf[s->n++] = c; + s->buf[s->n] = '\0'; +} + +static void string_free(struct string *s) { + free(s->buf); +} + json_object *parse(FILE *f, json_object *current) { int c = getc(f); if (c == EOF) { @@ -147,51 +174,49 @@ json_object *parse(FILE *f, json_object *current) { } if (c == '-' || (c >= '0' && c <= '9')) { -#define MAX 500 - char val[MAX]; - int off = 0; + struct string val; + string_init(&val); - val[off++] = c; + string_append(&val, c); if (c >= '1' && c <= '9') { c = peek(f); while (c >= '0' && c <= '9') { - val[off++] = getc(f); + string_append(&val, getc(f)); c = peek(f); } } if (peek(f) == '.') { - val[off++] = getc(f); + string_append(&val, getc(f)); c = peek(f); while (c >= '0' && c <= '9') { - val[off++] = getc(f); + string_append(&val, getc(f)); c = peek(f); } } c = peek(f); if (c == 'e' || c == 'E') { - val[off++] = getc(f); + string_append(&val, getc(f)); c = peek(f); if (c == '+' || c == '-') { - val[off++] = getc(f); + string_append(&val, getc(f)); } c = peek(f); while (c >= '0' && c <= '9') { - val[off++] = getc(f); + string_append(&val, getc(f)); c = peek(f); } } - val[off++] = '\0'; - json_object *n = add_object(JSON_NUMBER, current); - n->number = atof(val); + n->number = atof(val.buf); + string_free(&val); return n; }