From 6d578255208c231e9e08c81c474f17bd3986ecf8 Mon Sep 17 00:00:00 2001 From: my0sotis <35601060+my0sotis@users.noreply.github.com> Date: Fri, 27 Oct 2023 09:31:03 +0800 Subject: [PATCH] fix: overflow (#309) ### What problems were solved in this pull request? Problem: `compare_int` uses subtraction to determine the size of two integers, which may cause integer overflow and return incorrect results. ### How to reproduce When v1 is -2147483648 and v2 is 1, return 2147483647. Returned incorrect result due to integer overflow ### What is changed and how it works? Use comparison operators instead of subtraction. --- deps/common/lang/comparator.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/deps/common/lang/comparator.cpp b/deps/common/lang/comparator.cpp index 8ebd04c67..3214f6e17 100644 --- a/deps/common/lang/comparator.cpp +++ b/deps/common/lang/comparator.cpp @@ -23,7 +23,13 @@ int compare_int(void *arg1, void *arg2) { int v1 = *(int *)arg1; int v2 = *(int *)arg2; - return v1 - v2; + if (v1 > v2) { + return 1; + } else if (v1 < v2) { + return -1; + } else { + return 0; + } } int compare_float(void *arg1, void *arg2)