此代码如何产生无符号整数溢出
How does this code produce unsigned integer overflow
我有以下递归constexpr
函数
template<size_t N, size_t O,size_t All>
constexpr int get_indices(const std::array<size_t,N> &products,
const std::array<size_t,N>& idx,
const std::array<std::array<int,O>,All> &as_all,
int i,
int it) {
return it==0 ? as_all[i][idx[static_cast<int>(N)-1]] :
products[it]*as_all[i][idx[it]] +
get_indices(products,idx,as_all,i,it-1);
}
当使用调用时
constexpr std::array<size_t,2> products = {2,0};
constexpr std::array<size_t,2> idx = {0,1};
constexpr std::array<std::array<int,3>,8> as_all = {{{0, 0, 0},
{0, 0, 1},
{0, 1, 0},
{0, 1, 1},
{1, 0, 0},
{1, 0, 1},
{1, 1, 0},
{1, 1, 1}}};
get_indices(products,idx,as_all,4,2); // call it
它会产生垃圾结果。我认为这是一个无符号溢出的问题,但我不太确定它是如何发生的。我检查了gcc
和clang
。
您有一个越界访问,clang和gcc甚至告诉您:
实例
main.cpp:28:15: error: constexpr variable 'x' must be initialized by a constant expression
constexpr int x = get_indices(products,idx,as_all,4,2);
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
main.cpp:11:9: note: read of dereferenced one-past-the-end pointer is not allowed in a constant expression
products[it]*as_all[i][idx[it]] +
^
问题是您试图访问idx[2]
,而它的大小是2,因此您只能访问idx[0]
或idx[1]
相关文章:
- C++中无符号字符溢出
- 如何打印boost多精度128位无符号整数
- C++模板函数,用于比较任何无符号整数和有符号整数
- 在线程中读取无符号整数时,c++ 位是否以原子方式切换?
- Constexpr 可变参数模板,用于对无符号整数进行重新排序
- 为什么 Clang 和 GCC 中两个无符号整数之和的结果类型不同
- 从 std::string 转换为 const 无符号整数
- 迭代器和无符号整数的重载 + 运算符
- C++,概念不适用于无符号整数作为结果类型?
- 在C++中,将无符号整数转换为八进制表示,反之亦然的最佳方法是什么
- 原子式清除无符号整数的最低非零位
- 计算机使用什么方法添加无符号整数
- 隐式转换双重到无符号长溢出 c++
- 运行时错误:有符号整数溢出:964632435 * 10 无法在类型 'int' 中表示
- gcc(TDM-GCC)中的无符号整数溢出错误
- 如何抑制来自UBsan的一些无符号整数溢出错误
- C/ c++无符号整数溢出
- 此代码如何产生无符号整数溢出
- 发生整数溢出时无符号整数和有符号整数的行为差异
- 如何检测无符号整数溢出