mirror of
https://github.com/DaveGamble/cJSON.git
synced 2023-08-10 21:13:26 +03:00
cJSON_Print: Use reallocate if available
This can reduce worst case peak memory usage by 30% depending on the realloc implementation.
This commit is contained in:
27
cJSON.c
27
cJSON.c
@ -1055,17 +1055,28 @@ static unsigned char *print(const cJSON * const item, cJSON_bool format, const i
|
|||||||
}
|
}
|
||||||
update_offset(buffer);
|
update_offset(buffer);
|
||||||
|
|
||||||
/* copy the buffer over to a new one */
|
/* check if reallocate is available */
|
||||||
printed = (unsigned char*) hooks->allocate(buffer->offset + 1);
|
if (hooks->reallocate != NULL)
|
||||||
if (printed == NULL)
|
|
||||||
{
|
{
|
||||||
goto fail;
|
printed = (unsigned char*) hooks->reallocate(buffer->buffer, buffer->length);
|
||||||
|
buffer->buffer = NULL;
|
||||||
|
if (printed == NULL) {
|
||||||
|
goto fail;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
strncpy((char*)printed, (char*)buffer->buffer, min(buffer->length, buffer->offset + 1));
|
else /* otherwise copy the JSON over to a new buffer */
|
||||||
printed[buffer->offset] = '\0'; /* just to be sure */
|
{
|
||||||
|
printed = (unsigned char*) hooks->allocate(buffer->offset + 1);
|
||||||
|
if (printed == NULL)
|
||||||
|
{
|
||||||
|
goto fail;
|
||||||
|
}
|
||||||
|
memcpy(printed, buffer->buffer, min(buffer->length, buffer->offset + 1));
|
||||||
|
printed[buffer->offset] = '\0'; /* just to be sure */
|
||||||
|
|
||||||
/* free the buffer */
|
/* free the buffer */
|
||||||
hooks->deallocate(buffer->buffer);
|
hooks->deallocate(buffer->buffer);
|
||||||
|
}
|
||||||
|
|
||||||
return printed;
|
return printed;
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user