#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不是指向的一个大小的内存吗?
#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不是指向的一个大小的内存吗?
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.2k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.4k 阅读
1 回答3.3k 阅读
C的数组标识符,里面并没有包含该数组长度的信息,只包含地址信息,所以语言本身无法检查,只能通过编译器检查,而早期的C语言编译器也不对数组越界进行检查,只能由程序员自己检查确保。以及在早期的CRT函数中也不对字符串指针或数组进行越界检查,都是要求程序员确保空间足够,因此也才也才有了在VS2005之后微软提供的安全的CRT函数版本。即使越界也能正常编译通过,试着扩大一下范围,同时输出地址,可以看出,确实是访问了越界的地址
0x100500000
0x100509c40
1
Program ended with exit code: 0