这是我的代码
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
int* arr = new(nothrow)int [100];
int i;
if(arr == 0){//heap is full or dynamic allocation fails
cout<<"Cannot allocate memory\n";
return 0;
}
ofstream file("myFile.bin",ios::out|ios::binary);//opening the file in binary mode
for(i = 0;i<100;++i){//dynamic array which contains numbers form 0 to99
arr[i] = i;
}
if( file.is_open() ){
if( file.good() )
file.write((char*)arr,400);
delete [] arr;
file.close();
}
ifstream file1("myFile.bin",ios::in|ios::binary|ios::ate);
ifstream::pos_type size;
char* buff;
if(file1.is_open()){
size = file1.tellg();
buff = new char[size];
file1.seekg(0);
if( file1.good() )
file1.read(buff,size);
file1.close();
for(i=0;i<size;i= i+4){//gcc => sizeof(int) is 4
cout<<(int)*(buff+i)<<" ";
}
delete [] buff;
}
}
这里我只分配了 100 个字节,我存储的是 0-99 之间的整数。 400 字节(海合会)。 我正在访问未分配的内存。没有发生段错误。 为什么会这样?
输出为 0 1 2 3....99
最佳答案
实际上,您还没有分配 100 个字节。您已经分配了 100 个 int
。这里没有超限。
关于c++ - C++ 中的动态分配不检查数组边界?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9363747/