Search code examples
c++arraysdynamic-memory-allocationstatic-memory-allocation

why cpp allows to get a access to memory i haven't allocated?


In cpp one can use an array declaration as typename array[size]; or typename *array = new typename[size]; Where array is of length 'size' and elements are indexed from '0' to 'size -1' Here my question is am I allowed to access the elements beyond the index >= size.

So I wrote this little code to check it

#include <iostream>
using namespace std;

int main()
{
    //int *c;                    //for dynamic allocation
    int n;                       //length of the array c
    cin>>n;                      //getting the length
    //c = new int[n];            //for dynamic allocation
    int c[n];                    //for static allocation

    for(int i=0; i<n; i++)       //getting the elements
        cin>>c[i];

    for(int i=0; i<n+10; i++)    //showing the elements, I have add up 10
        cout<<c[i]<<" ";         //with size to access the memory I haven't
                                 //allocated for
    return 0;
}

And the result is like this

2
1 2
1 2 2686612 1970422009 7081064 4199040 2686592 0 1 1970387429 1971087432 2686700

Shouldn't the program crashed but gives garbage values. And for both the allocation methods it gives the same result. It makes more bugs which are hard to detect. Is it related with the environment or the compiler I am using or anything else?

I was using codeblocks IDE having TDM-GCC 4.8.1 compiler on windows 8.1

Thanks in advance.


Solution

  • The c++ compilers don't enforce this as there is no specification to do so.

    When you access an element of an array there is no boundary check done. c[i] just gets translated to c + i * sizeof(int) and that's it. If that area of memory is not initialize you'll get garbage, but you could be getting other useful information it all depends on what is there.

    Please note that depending on the OS and the c++ runtime you're running you can get different results, for instance on a linux box you'll probably be getting a segmentation fault and the program will crash.