84669 personnes étudient
152542 personnes étudient
20005 personnes étudient
5487 personnes étudient
7821 personnes étudient
359900 personnes étudient
3350 personnes étudient
180660 personnes étudient
48569 personnes étudient
18603 personnes étudient
40936 personnes étudient
1549 personnes étudient
1183 personnes étudient
32909 personnes étudient
#include <iostream> #include <cstring> #include <string> using namespace std; int main() { int* str = new int[1]; str[2] = 1; cout << str[2] << endl; return 0; }
为什么这段代码可以正常运行哦?str不是指向的一个大小的内存吗?
闭关修行中......
C的数组标识符,里面并没有包含该数组长度的信息,只包含地址信息,所以语言本身无法检查,只能通过编译器检查,而早期的C语言编译器也不对数组越界进行检查,只能由程序员自己检查确保。以及在早期的CRT函数中也不对字符串指针或数组进行越界检查,都是要求程序员确保空间足够,因此也才也才有了在VS2005之后微软提供的安全的CRT函数版本。即使越界也能正常编译通过,试着扩大一下范围,同时输出地址,可以看出,确实是访问了越界的地址
#include <iostream> #include <cstring> #include <string> using namespace std; int main() { int* str = new int[1]; str[10000] = 1; cout << str << endl; cout << &str[10000] << endl; cout << str[10000] << endl; return 0; }
0x1005000000x100509c401Program ended with exit code: 0
不是没有问题,只是恰好没出现错误而已。你访问了一个不属于你的空间,而那个空间恰好没人在使用,所以看起来没问题。
C的数组标识符,里面并没有包含该数组长度的信息,只包含地址信息,所以语言本身无法检查,只能通过编译器检查,而早期的C语言编译器也不对数组越界进行检查,只能由程序员自己检查确保。以及在早期的CRT函数中也不对字符串指针或数组进行越界检查,都是要求程序员确保空间足够,因此也才也才有了在VS2005之后微软提供的安全的CRT函数版本。即使越界也能正常编译通过,试着扩大一下范围,同时输出地址,可以看出,确实是访问了越界的地址
0x100500000
0x100509c40
1
Program ended with exit code: 0
不是没有问题,只是恰好没出现错误而已。
你访问了一个不属于你的空间,而那个空间恰好没人在使用,所以看起来没问题。