Search code examples
c++filedynamic-memory-allocation

Dynamic allocation in c++ is not checking array boundary?


Here is my code

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

    }



}

Here i have allocated only 100 bytes and i am storing integers from 0-99 .ie. 400 bytes (gcc). I am accessing memory that is not allocated.No segmentation fault occured . Why is it happening.?

Output is 0 1 2 3....99


Solution

  • Actually, you haven't allocated 100 bytes. You've allocated 100 ints. There's no overrun here.