Fix undefined behavior of signed integer overflow

Testing for overflow by adding a value to a variable to see if it "wraps
around" works only for unsigned integer values. Signed integer overflow
is undefined behavior in C and C++.
This commit is contained in:
Mingjie Shen 2024-02-13 14:02:31 -05:00
parent 3fa2360720
commit 2fa2a9480a

View File

@ -36,6 +36,7 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <math.h> #include <math.h>
#include <limits.h>
#include "linmath.h" #include "linmath.h"
@ -103,7 +104,7 @@ static void key_callback(GLFWwindow* window, int key, int scancode, int action,
{ {
case GLFW_KEY_UP: case GLFW_KEY_UP:
{ {
if (swap_interval + 1 > swap_interval) if (swap_interval <= INT_MAX - 1)
set_swap_interval(window, swap_interval + 1); set_swap_interval(window, swap_interval + 1);
break; break;
} }
@ -112,12 +113,12 @@ static void key_callback(GLFWwindow* window, int key, int scancode, int action,
{ {
if (swap_tear) if (swap_tear)
{ {
if (swap_interval - 1 < swap_interval) if (swap_interval >= INT_MIN + 1)
set_swap_interval(window, swap_interval - 1); set_swap_interval(window, swap_interval - 1);
} }
else else
{ {
if (swap_interval - 1 >= 0) if (swap_interval >= 1)
set_swap_interval(window, swap_interval - 1); set_swap_interval(window, swap_interval - 1);
} }
break; break;