undefined behavior in gcd when parameters are minimum values of signed integers
- 主要语言
- C++
- 星标
- 19
- 派生
- 58
- PR 合并指标
- 30 天内没有已合并 PR
描述
This is being reported to me via a clang-analyzer check, and it refers to the gcd template function in common_factor_rt.hpp
Integer template parameter type is a signed integer, and both parameters ('a' and 'b') are std::numeric_limits\::min.
```
444 template
445 inline BOOST_CXX14_CONSTEXPR Integer gcd(Integer const &a, Integer const &b) BOOST_GCD_NOEXCEPT(Integer)
446 {
447 if(a == (std::numeric_limits::min)())
448 return a == static_cast(0) ? gcd_detail::gcd_traits::abs(b) : boost::integer::gcd(static_cast(a % b), b);
449 else if (b == (std::numeric_limits::min)())
450 return b == static_cast(0) ? gcd_detail::gcd_traits::abs(a) : boost::integer::gcd(a, static_cast(b % a));
451 return gcd_detail::optimal_gcd_select(static_cast(gcd_detail::gcd_traits::abs(a)), static_cast(gcd_detail::gcd_traits::abs(b)));
452 }
```
In the initial invocation, the condition on 447 is true, and the condition on 448 is false. This leads to a recursive call to the function with parameters a=0 and b=std::numeric_limits\::min.
In the recursive call, the condition on 447 is false, the condition on 449 is true, and the condition on 450 is false. Another recursive call is on-deck with a=0 and b=b%a, But a is zero at this point. Anything mod 0 is undefined behavior.
My suggested fix is to check if a and b are the same value at the start of the function, and return a right away.
贡献指南
这个仓库没有索引到贡献指南
调研方向
从 common_factor_rt.hpp 中 444-451 行附近的 gcd 模板开始,复现将两个有符号参数都设置为 std::numeric_limits::min() 的调用。跟踪递归路径,并验证最小值情况不再到达除以零的取模操作。如果 repository 提供了相关的 gcd 测试位置,请添加或更新回归测试覆盖。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- cpp
- 领域
- backend
- Issue 类型
- 缺陷
- 难度
- 2/5
- 预计耗时
- 1-3 小时
- 活跃度
- 停滞
- 描述清晰度
- 描述清楚
- 新手友好度
- 45/100