Fix json_loadf and json_loadfd with empty input

Nothing was appended to strbuffer, so the buffer was left empty. An
empty strbuffer is not an empty string but NULL, so the result was a
segfault.

This patch fixes the problem by initializing strbuffer to an empty
string.
This commit is contained in:
Petri Lehtinen 2009-06-22 21:09:25 +03:00
parent dc9b954b62
commit b1fe723a7f
4 changed files with 22 additions and 14 deletions

View File

@ -214,7 +214,8 @@ char *json_dumps(const json_t *json, uint32_t flags)
strbuffer_t strbuff;
char *result;
strbuffer_init(&strbuff);
if(strbuffer_init(&strbuff))
return NULL;
if(do_dump(json, flags, 0, dump_to_strbuffer, (void *)&strbuff))
return NULL;

View File

@ -499,7 +499,8 @@ json_t *json_loadf(FILE *input, json_error_t *error)
size_t length;
json_t *result = NULL;
strbuffer_init(&strbuff);
if(strbuffer_init(&strbuff))
return NULL;
while(1)
{
@ -531,7 +532,8 @@ json_t *json_loadfd(int fd, json_error_t *error)
ssize_t length;
json_t *result = NULL;
strbuffer_init(&strbuff);
if(strbuffer_init(&strbuff))
return NULL;
while(1)
{

View File

@ -7,17 +7,25 @@
#define STRBUFFER_MIN_SIZE 16
#define STRBUFFER_FACTOR 2
void strbuffer_init(strbuffer_t *strbuff)
int strbuffer_init(strbuffer_t *strbuff)
{
strbuff->value = NULL;
strbuff->size = STRBUFFER_MIN_SIZE;
strbuff->length = 0;
strbuff->size = 0;
strbuff->value = malloc(strbuff->size);
if(!strbuff->value)
return -1;
memset(strbuff->value, 0, strbuff->size);
return 0;
}
void strbuffer_close(strbuffer_t *strbuff)
{
free(strbuff->value);
strbuffer_init(strbuff);
strbuff->size = 0;
strbuff->length = 0;
strbuff->value = NULL;
}
const char *strbuffer_value(strbuffer_t *strbuff)
@ -39,13 +47,10 @@ int strbuffer_append(strbuffer_t *strbuff, const char *string)
int strbuffer_append_bytes(strbuffer_t *strbuff, const char *data, int size)
{
if(strbuff->length + size > strbuff->size)
if(strbuff->length + size >= strbuff->size)
{
if(strbuff->length == 0)
strbuff->size = max(size + 1, STRBUFFER_MIN_SIZE);
else
strbuff->size = max(strbuff->size * STRBUFFER_FACTOR,
strbuff->length + size + 1);
strbuff->size = max(strbuff->size * STRBUFFER_FACTOR,
strbuff->length + size + 1);
strbuff->value = realloc(strbuff->value, strbuff->size);
if(!strbuff->value)

View File

@ -7,7 +7,7 @@ typedef struct {
int size;
} strbuffer_t;
void strbuffer_init(strbuffer_t *strbuff);
int strbuffer_init(strbuffer_t *strbuff);
void strbuffer_close(strbuffer_t *strbuff);
const char *strbuffer_value(strbuffer_t *strbuff);