Skip to content

Commit

Permalink
fix: bsearch prevent overflow on mid calculation
Browse files Browse the repository at this point in the history
Signed-off-by: Eloy Coto <eloy.coto@acalustra.com>
  • Loading branch information
eloycoto committed Feb 29, 2024
1 parent 95cbcc5 commit 4f1ea42
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/builtin.c
Original file line number Diff line number Diff line change
Expand Up @@ -785,13 +785,14 @@ static jv f_sort_by_impl(jq_state *jq, jv input, jv keys) {
/* If the input is not sorted, bsearch will terminate but with irrelevant results. */
static jv f_bsearch(jq_state *jq, jv input, jv target) {
if (jv_get_kind(input) != JV_KIND_ARRAY) {
jv_free(input);
return type_error(input, "cannot be searched from");
}
int start = 0;
int end = jv_array_length(jv_copy(input));
jv answer = jv_invalid();
while (start < end) {
int mid = (start + end) / 2;
int mid = start + (end - start) / 2;
int result = jv_cmp(jv_copy(target), jv_array_get(jv_copy(input), mid));
if (result == 0) {
answer = jv_number(mid);
Expand Down
4 changes: 4 additions & 0 deletions tests/jq.test
Original file line number Diff line number Diff line change
Expand Up @@ -1559,6 +1559,10 @@ bsearch({x:1})
[{ "x": 0 },{ "x": 1 },{ "x": 2 }]
1

bsearch(0)
"aa"
jq: error (at <unknown>): string ("aa") cannot be searched from

# strptime tests are in optional.test

strftime("%Y-%m-%dT%H:%M:%SZ")
Expand Down

0 comments on commit 4f1ea42

Please sign in to comment.