问题是,即使结果 包含数组中的10个数字,它也会将计数值打印为'11'。
如果我正确理解这一点,您将访问大小为10的数组的第10个索引,这是未定义的行为,因为它超出了边界访问范围。
如果您使用C++ 03,你能避免原阵列的使用和喜欢std::vector
。 std::vector
自动处理内存,为您和其at()
成员函数,如果你尝试提供一个出界指数会抛出异常。被警告operator[]
不提供边界检查。
在C++ 11,可以使用std::array
。到std::vector
相似,它有at()
提供边界检查和operator[]
哪些没有。非成员函数std::get
提供编译时边界检查。这里有一个例子:
std::array<int, 5> arr { 1, 2, 3, 4, 5 };
std::get<6>(arr);
// error: static assertion failed: index is out of bounds
arr.at(6);
// terminate called after throwing an instance of 'std::out_of_range'
// what(): array::at: __n (which is 6) >= _Nm (which is 5)
如果你坚持原始阵列,编译器可能会与帮助抓出界失误,如LLVM的不确定行为消毒(这已经被移植到GCC的诊断或工具)和Valgrind的(所报道的内存错误)下面是锵给人的出界警告的例子:
int arr[5] = { 1, 2, 3, 4, 5 };
arr[6];
// warning: array index 6 is past the end of the array (which contains 5 elements) [-Warray-bounds]
和消息,如果你有-fsanitize=address,undefined
运行它,您将获得:
runtime error: index 6 out of bounds for type 'int [5]'
GCC在一个循环中捕获未定义行为:
for (int i = 0; i < 6; ++i)
std::cout << arr[i];
// warning: iteration 5u invokes undefined behavior [-Waggressive-loop-optimizations]
这是使用-Wall -Wextra -pedantic
,这两种编译器的工作奠定了良好的说法,但被警告,你得到确切的诊断各不相同,所以总是测试多代码工具。
那么,你基本上是试图增加边界检查,基本数组? – 2014-11-01 15:48:15
是的,这将是一种说法。 – 2014-11-01 15:51:00
由于您使用的是C++,因此宁愿使用'std :: array'或'std :: vector'。 'at()'成员函数提供了运行时边界检查,而'std :: get'提供了编译时间边界检查。否则,请考虑使用静态分析工具或clang和gcc的'-fsanitize = undefined'。海湾合作委员会也可能通过警告超出界限。 – 2014-11-01 15:52:16