diff --git a/cJSON.c b/cJSON.c index 00e87d2..e6372a7 100644 --- a/cJSON.c +++ b/cJSON.c @@ -220,21 +220,40 @@ typedef struct int offset; } printbuffer; -static char* ensure(printbuffer *p,int needed) +/* realloc printbuffer if necessary to have at least "needed" bytes more */ +static char* ensure(printbuffer *p, int needed) { - char *newbuffer;int newsize; - if (!p || !p->buffer) return 0; - needed+=p->offset; - if (needed<=p->length) return p->buffer+p->offset; + char *newbuffer; + int newsize; + if (!p || !p->buffer) + { + return 0; + } + needed += p->offset; + if (needed <= p->length) + { + return p->buffer + p->offset; + } - newsize=pow2gt(needed); - newbuffer=(char*)cJSON_malloc(newsize); - if (!newbuffer) {cJSON_free(p->buffer);p->length=0,p->buffer=0;return 0;} - if (newbuffer) memcpy(newbuffer,p->buffer,p->length); - cJSON_free(p->buffer); - p->length=newsize; - p->buffer=newbuffer; - return newbuffer+p->offset; + newsize = pow2gt(needed); + newbuffer = (char*)cJSON_malloc(newsize); + if (!newbuffer) + { + cJSON_free(p->buffer); + p->length = 0; + p->buffer = 0; + + return 0; + } + if (newbuffer) + { + memcpy(newbuffer, p->buffer, p->length); + } + cJSON_free(p->buffer); + p->length = newsize; + p->buffer = newbuffer; + + return newbuffer + p->offset; } static int update(printbuffer *p)