【问题标题】:Initializer list overwrites memory for dynamic multi dimensional array初始化器列表覆盖动态多维数组的内存
【发布时间】:2016-10-01 02:09:34
【问题描述】:

为什么允许以下行为?

#include <iostream>
#include <random>

int main()
{
    std::random_device rd;
    std::uniform_int_distribution<int> dist(2,3);

    auto arr = new int[dist(rd)][4][2]{{{1}},{{2}},{{3}}}; // may write to unallocated memory

    auto val1 = arr[0][0][0];
    auto val2 = arr[1][0][0];
    auto val3 = arr[2][0][0];

    auto result = val1 + val2 + val3;
    std::cout << result;

    return 0;
}

如果随机值为 2,初始化器将覆盖未分配的内存。

与找到的答案 here 类似,我没想到编译器会允许这样做。

【问题讨论】:

    标签: c++


    【解决方案1】:

    如果 array-new 表达式的初始值设定项过多,编译器需要生成 bad_array_new_length 类型的异常抛出。

    g++ 6.1 确实像预期的那样抛出了bad_array_new_length; clang 没有,但这是因为它能够消除分配 (Clang fails to throw a std::bad_alloc when allocating objects that would exceed the limit)。如果强制进行分配,clang 会抛出异常但of the wrong type (std::bad_alloc)。

    Example:

    terminate called after throwing an instance of 'std::bad_array_new_length'
      what():  std::bad_array_new_length
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-27
      • 2011-10-30
      • 1970-01-01
      • 1970-01-01
      • 2016-08-16
      • 2020-05-04
      • 2015-08-01
      相关资源
      最近更新 更多