Corrected realloc to free old buffer, initialized ptr to NULL

This commit is contained in:
ares 2020-11-30 08:43:29 -05:00
parent 934accc47e
commit 01ae62f74f

View File

@ -3060,8 +3060,9 @@ CJSON_PUBLIC(int) cJSON_saveJSONfile(const char *filename, cJSON *item, char *er
#define cJSON_LOAD_BUFFER_INCREMENT 2048 #define cJSON_LOAD_BUFFER_INCREMENT 2048
CJSON_PUBLIC(int) cJSON_loadJSONfile(const char *filename, cJSON **item, char *errorMessage) { CJSON_PUBLIC(int) cJSON_loadJSONfile(const char *filename, cJSON **item, char *errorMessage) {
FILE *fptr; FILE *fptr = NULL;
char *buffer; char *buffer = NULL;
char *oldBuffer = NULL;
size_t bufferSize = cJSON_LOAD_BUFFER_INCREMENT; size_t bufferSize = cJSON_LOAD_BUFFER_INCREMENT;
size_t bytesRead = 0; size_t bytesRead = 0;
int i = 0; int i = 0;
@ -3100,12 +3101,14 @@ CJSON_PUBLIC(int) cJSON_loadJSONfile(const char *filename, cJSON **item, char *e
fclose(fptr); fclose(fptr);
return -1; return -1;
} }
/* Read in the file until there's nothing left to read /* Read in the file until there's nothing left to read
Keep reading in the file, expanding our buffer if needed */ Keep reading in the file, expanding our buffer if needed */
while ((bytesRead = fread(buffer + (cJSON_LOAD_BUFFER_INCREMENT * i), 1, cJSON_LOAD_BUFFER_INCREMENT, fptr)) > 0) { while ((bytesRead = fread(buffer + (cJSON_LOAD_BUFFER_INCREMENT * i), 1, cJSON_LOAD_BUFFER_INCREMENT, fptr)) > 0) {
if (bytesRead == sizeof(buffer)) if (bytesRead == sizeof(buffer))
{ {
/* We filled the buffer, realloc the final buffer so it's larger */ /* We filled the buffer, realloc the final buffer so it's larger */
oldBuffer = buffer;
buffer = (char *)realloc(buffer, bufferSize + cJSON_LOAD_BUFFER_INCREMENT); buffer = (char *)realloc(buffer, bufferSize + cJSON_LOAD_BUFFER_INCREMENT);
if (buffer == NULL) if (buffer == NULL)
{ {
@ -3113,6 +3116,7 @@ CJSON_PUBLIC(int) cJSON_loadJSONfile(const char *filename, cJSON **item, char *e
{ {
sprintf(errorMessage, "Memory allocation error while reading '%.420s'.", filename); sprintf(errorMessage, "Memory allocation error while reading '%.420s'.", filename);
} }
free(oldBuffer);
fclose(fptr); fclose(fptr);
return -2; return -2;
} }