Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parse error when arrays are empty #46

Closed
mboelstra opened this issue Jun 30, 2014 · 5 comments
Closed

Parse error when arrays are empty #46

mboelstra opened this issue Jun 30, 2014 · 5 comments

Comments

@mboelstra
Copy link

Hi,

The parser fails when the following JSON is provided: {"myArray": [] }

In code:
static char str[] = "{ "myArray": [] }";
json_value * root = json_parse(str, strlen(str));

This is because malloc is called with a size of 0, due to the empty array. However some implementations of malloc will return NULL when asked to allocate 0 bytes and in this case the parser stops. I think this is wrong. In my opinion the parser should not try to allocate 0 bytes. A simple check in the newValue method for the json_array case can prevent this:

In code:
if (value->u.array.length == 0) {
break;
}

With these three lines of code the parser can also handle the above input.

Regards,
Matthijs

@jamesamcl
Copy link
Collaborator

Thanks, I didn't know malloc could do that. In 63be13a I made it so that json_alloc allocates 1 byte if you request zero, just because I like the peace of mind that alloc always returns a valid pointer if it succeeds.

@jamesamcl
Copy link
Collaborator

And then changed my mind and did it your way in 8c4b18f because I realised my way violated the "[never] allocates more memory than it needs" claim.

Do you have a name for the AUTHORS file?

@mboelstra
Copy link
Author

This website (http://www.cplusplus.com/reference/cstdlib/malloc/) says the return value of malloc is implementation defined when allocating 0 bytes.
You have to be sure the memory is freed. So just allocating 1 byte can be dangerous.

On 30 jun. 2014, at 18:27, James McLaughlin notifications@github.com wrote:

Thanks, I didn't know malloc could do that. In 63be13a I made it so that json_alloc allocates 1 byte if you request zero, just because I like the peace of mind that alloc always returns a valid pointer if it succeeds.


Reply to this email directly or view it on GitHub.

@mboelstra
Copy link
Author

My full name is: Matthijs Boelstra

Thanx!

On 30 jun. 2014, at 18:31, James McLaughlin notifications@github.com wrote:

And then changed my mind and did it your way in 8c4b18f because I realised my way violated the "[never] allocates more memory than it needs" claim.

Do you have a name for the AUTHORS file?


Reply to this email directly or view it on GitHub.

@jamesamcl
Copy link
Collaborator

Thank you. 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants