diff --git a/cpp/src/gandiva/precompiled/string_ops.cc b/cpp/src/gandiva/precompiled/string_ops.cc index 7450018a556f..0b787f461c21 100644 --- a/cpp/src/gandiva/precompiled/string_ops.cc +++ b/cpp/src/gandiva/precompiled/string_ops.cc @@ -841,7 +841,12 @@ const char* repeat_utf8_int32(gdv_int64 context, const char* in, gdv_int32 in_le *out_len = 0; return ""; } - *out_len = repeat_number * in_len; + if (ARROW_PREDICT_FALSE( + arrow::internal::MultiplyWithOverflow(repeat_number, in_len, out_len))) { + gdv_fn_context_set_error_msg(context, "Would overflow maximum output size"); + *out_len = 0; + return ""; + } char* ret = reinterpret_cast(gdv_fn_context_arena_malloc(context, *out_len)); if (ret == nullptr) { gdv_fn_context_set_error_msg(context, "Could not allocate memory for output string"); diff --git a/cpp/src/gandiva/precompiled/string_ops_test.cc b/cpp/src/gandiva/precompiled/string_ops_test.cc index ca2b2b57856a..e0248667e3df 100644 --- a/cpp/src/gandiva/precompiled/string_ops_test.cc +++ b/cpp/src/gandiva/precompiled/string_ops_test.cc @@ -387,6 +387,13 @@ TEST(TestStringOps, TestRepeat) { EXPECT_EQ(std::string(out_str, out_len), ""); EXPECT_THAT(ctx.get_error(), ::testing::HasSubstr("Repeat number can't be negative")); ctx.Reset(); + + out_str = repeat_utf8_int32(ctx_ptr, "aa", 2, + std::numeric_limits::max() / 2 + 1, &out_len); + EXPECT_EQ(std::string(out_str, out_len), ""); + EXPECT_THAT(ctx.get_error(), + ::testing::HasSubstr("Would overflow maximum output size")); + ctx.Reset(); } TEST(TestStringOps, TestCastBoolToVarchar) {