Why am I able to access array elements "outside" of its range?

1.5k views Asked by At

I have a strange dilemma of sorts. I have been working with dynamically created arrays and pointer arithmetic in C/C++ for the past couple of weeks and find it very interesting. However, I noticed something "bad" that I'm kind of scared of. Here's my code:

#include <iostream>
#include <cstdlib>

using namespace std;

int main() {
    int *A = (int*) malloc(sizeof(int)*5);
    int B[5] = {0,1,2,3,4};
    A[0] = 0;
    A[1] = 1;
    A[2] = 2;
    A[3] = 3;
    A[4] = 4;
    A[5] = 5;
    A[12] = 12;
    //A[1000] = 1000;
    cout << "A[0] = " << A[0] << ", A[1] = " << A[1] << endl;
    cout << "A[2] = " << A[2] << ", A[3] = " << A[3] << endl;
    cout << "A[4] = " << A[4] << endl;
    cout << "A[12] = " << A[12] << ", A[5] =  " << A[5] << endl;
    cout << "A[1000] = " << A[1000] << endl;
    cout << "*(A+5) = " << *(A+5) << endl;
    B[5] = 5;
    cout << "B[5] = " << B[5] << endl;
    cout << "*(B+5) = " << *(B+5) << endl;
    /**********************************/
    return 0;
}

Notice that this code is not written in chronological order, but edited over time as I kept experimenting.

Anyhow, the code compiles just fine and I get the following output:

A[0] = 0, A[1] = 1
A[2] = 2, A[3] = 3
A[4] = 4
A[12] = 12, A[5] =  5
A[1000] = 0
*(A+5) = 5
B[5] = 5
*(B+5) = 5

Shouldn't A and B only be able to hold 5 values? Or is what I'm doing very dangerous? What is to stop someone from tampering with A[2000] if it is some sensitive piece of memory? Is this an actual problem, and if it is, does C++ have any pre-cautions for this situation?

1

There are 1 answers

1
riodoro1 On BEST ANSWER

Accessing array out of it's bounds is undefined behaviour, which means that anything can happen, even nothing. You could be reading some prohibited memory and cause "Access violation" or You could be reading some of Your other variables or some ancient data that was left there by somebody else who is long gone, it depends on where Your array is in memory and how far You wander off.

In C and C++ there is no run time boundary checking, this allows You to put any number in the subscript and in fact You will access the address expressed as follows: (address to first element)+sizeof(type)*subscript