DaveGamble / cJSON

Ultralightweight JSON parser in ANSI C
MIT License
10.83k stars 3.22k forks source link

cJSON_GetArraySize overflow #795

Closed VNovytskyi closed 1 year ago

VNovytskyi commented 1 year ago

Hello! Can someone explain to me the FIXME message in the function cJSON_GetArraySize?

cJSON.c:1827

/* Get Array size/item / object item. */
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array)
{
    cJSON *child = NULL;
    size_t size = 0;

    if (array == NULL)
    {
        return 0;
    }

    child = array->child;

    while(child != NULL)
    {
        size++;
        child = child->next;
    }

    /* FIXME: Can overflow here. Cannot be fixed without breaking the API */

    return (int)size;
}

I am developing the wrapper module for the cJSON library and can use my own implementation of this function.

daschfg commented 1 year ago

Not the author, but from what I understand: The proper type to handle the array size would be size_t, as is done inside the function. But due to backward compatibility, the return type has to stay int.

This is problematic for two reasons: Usually size_t would be defined as an unsigned type, while int is a signed type. Additionally, depending on the target architecture they could be values of different size.

Both these points could potentially pose a problem (overflow) for very large arrays, hence the FIXME.