c++ - C++ 中的动态分配不检查数组边界?

标签 c++ file dynamic-memory-allocation

这是我的代码

#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/

相关文章:

c++ -/usr/bin/ld : cannot find -lgd

c++ - 离开作用域时不调用析构函数

java - 如何将文件写入目录?

c - C 中的内存访问冲突 : Trying to write substrings from char** to char**

c - 使用 realloc 缩小

c++ - Clang 格式在单行上链接 else ifs

c++ - 是否允许递归初始化数组?

c++ - 逐行读取文件

java - 在 JAVA 中读取文件,equals 不起作用

c++ - 当 QObject 被销毁时,Qt 可以安排将 QObject* 设置为 nullptr 吗?