title: Why am I able to access array elements "outside" of its range?
body: <p>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:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;cstdlib&gt;
  
  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 &lt;&lt; "A[0] = " &lt;&lt; A[0] &lt;&lt; ", A[1] = " &lt;&lt; A[1] &lt;&lt; endl;
      cout &lt;&lt; "A[2] = " &lt;&lt; A[2] &lt;&lt; ", A[3] = " &lt;&lt; A[3] &lt;&lt; endl;
      cout &lt;&lt; "A[4] = " &lt;&lt; A[4] &lt;&lt; endl;
      cout &lt;&lt; "A[12] = " &lt;&lt; A[12] &lt;&lt; ", A[5] =  " &lt;&lt; A[5] &lt;&lt; endl;
      cout &lt;&lt; "A[1000] = " &lt;&lt; A[1000] &lt;&lt; endl;
      cout &lt;&lt; "*(A+5) = " &lt;&lt; *(A+5) &lt;&lt; endl;
      B[5] = 5;
      cout &lt;&lt; "B[5] = " &lt;&lt; B[5] &lt;&lt; endl;
      cout &lt;&lt; "*(B+5) = " &lt;&lt; *(B+5) &lt;&lt; endl;
      /**********************************/
      return 0;
  }
  </code></pre>
  
  <p>Notice that this code is not written in chronological order, but edited over time as I kept experimenting.</p>
  
  <p>Anyhow, the code compiles just fine and I get the following output:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>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?</p>