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

Invalid floating point exception with cJSON_CreateNumber(NAN) #891

Open
guillaumechereau opened this issue Sep 4, 2024 · 0 comments
Open

Comments

@guillaumechereau
Copy link

Calling cJSON_CreateNumber(NAN) raises a FE_INVALID floating point exception.

Here is a sample code that shows the problem:

#define _GNU_SOURCE

#include "cJSON.h"

#include <fenv.h>
#include <math.h>
#include <stdio.h>

int main()
{
    feenableexcept(FE_INVALID); // Crashes on FE_INVALID.
    cJSON *n = cJSON_CreateNumber(NAN);
    printf("n: %d %f\n", n->valueint, n->valuedouble);
    cJSON_Delete(n);
}

While I guess this is technically not a bug, I think it would be nice if the library tested for NAN in cJSON_CreateNumber to avoid this, and also set the int value to a constant. Maybe something like:

        item->type = cJSON_Number;
        item->valuedouble = num;

        if (isnan(num)) {
            item->valueint = 0;
        }
        /* use saturation in case of overflow */
        else if (num >= INT_MAX)
       ...
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

1 participant