C/C++编译器中数组越界却不会报错崩溃
平时编码的话数组一般都用STL标准库的vector或map等,很少使用int[10]这种自己写的,今天偶然看到别人代码的奇怪bug,一直找不到原因,后来突然想到是不是数组越界没有报错导致?但又不敢肯定了,因为STL标准库越界直接就崩溃报错了,对于自己写的数组还是测试一下吧。 代码如下:
#include "pch.h" #include <iostream> #include "Piece.h" int main() { Piece m_Pieces[16]; for (int i = 0; i < 16; i++) { m_Pieces[i].init(i); } int nTemp = -1; cout << m_Pieces[nTemp].m_bRed << endl; int nPos[5]; for (int i = 0; i < 4; i++) { nPos[i] = i; } int nTemp2 = 6; cout << nPos[nTemp] << endl; cout << nPos[nTemp2] << endl; bool bValue1 = true; bool bValue2 = true; if (bValue1 == bValue2) { std::cout << "It is same! "; } else { std::cout << "It is different! "; } }
可以看到,无论对于自定义类数组还是int型数组,故意越界取值时并不会提示报错或崩溃,而是输出一个特殊值直接往下运行。记录一下谨记此问题吧。