这里是我的代码C++中的动态分配不检查数组边界?
#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 .IE存储整数。 400字节(gcc)。 我正在访问未分配的内存。未发生分段错误。 为什么会这样。
输出是0 1 2 3 .... 99
只是幸运。其实,只是回来运气。 – pmr 2012-02-20 15:38:03
“这里我只分配了100个字节”。这是哪里”?我看到两个'new'表达式,'new(nothrow)int [100];'和'buff = new char [size];'。你认为哪一个是100字节? – 2012-02-20 15:45:55
第一个类型int..already得到了答案:) – 2012-02-20 16:31:37