cJSON icon indicating copy to clipboard operation
cJSON copied to clipboard

Invalid floating point exception with cJSON_CreateNumber(NAN)

Open guillaumechereau opened this issue 1 year ago • 0 comments

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)
       ...

guillaumechereau avatar Sep 04 '24 16:09 guillaumechereau