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?
 
     
    