jkuhlmann / cgltf

:diamond_shape_with_a_dot_inside: Single-file glTF 2.0 loader and writer written in C99
MIT License
1.42k stars 135 forks source link

Potential Undefined Behaviour in "cgltf_component_read_index" #214

Closed Themperror closed 1 year ago

Themperror commented 1 year ago

Hello,

The following case can trigger undefined behaviour:

case cgltf_component_type_r_32f:
    return (cgltf_size)*((const float*) in);

in the case that in ever refers to a float that is negative, the result returned is undefined and actively differs between x86 and ARM

directly casting negative floats to unsigned integers is not valid, ARM will clamp to zero and x86 will overflow

The fix is very easy: return (cgltf_size)((cgltf_ssize)*((const float*) in));

by casting the result to a signed integer first and then casting it to an unsigned integer the behaviour will be entirely defined and consistent amongst architectures.