【发布时间】:2012-10-13 21:09:54
【问题描述】:
在 C++11 中,如果我们尝试使用全局运算符 new 分配负大小的数组,它将抛出 std::bad_array_new_length,但是 C++98 / C++03 呢?是 UB 还是会抛出 std::bad_alloc?
int main()
{
int* ptr = new int[-1];
}
【问题讨论】:
标签: c++
在 C++11 中,如果我们尝试使用全局运算符 new 分配负大小的数组,它将抛出 std::bad_array_new_length,但是 C++98 / C++03 呢?是 UB 还是会抛出 std::bad_alloc?
int main()
{
int* ptr = new int[-1];
}
【问题讨论】:
标签: c++
如果大小为 C++03 标准的负 5.3.4p6,则程序不正确:
direct-new-declarator 中的每个常量表达式都应是一个整数常量表达式 (5.19),并计算为 严格的正值。 direct-new-declarator 中的表达式应为具有非负值的整数或枚举类型 (3.9.1)。
以上引用涵盖new T[a][b];,其中b是根据语法的常量表达式,a是表达式(只有第一个维度)。
【讨论】:
const size_t s = -1; int* ptr = new int[s]; s 是绝对正数吗?
size_t 也被指定为无符号类型。编辑:是的,是的。
new[] 的定义表明它需要一个无符号整数,也类型定义为size_t。所以 应该 永远不会编译。
见这里http://en.cppreference.com/w/cpp/types/size_t(这是一个无符号整数)。
【讨论】:
你可以通过int a[-1]得到这个:
prog.cpp: In function ‘int main()’:
prog.cpp:4: error: size of array ‘b’ is negative
这对于int* a = new int[-1](运行时错误):
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
【讨论】: