title: Printing a malloc() declared array - A very short code that prints out of bounds?
body: <p>Why does my program print an extra element, which looks like a memory location?</p>
  
  <p>CODE:</p>
  
  <pre><code>#include&lt;stdio.h&gt;
  #include&lt;stdlib.h&gt;
  
  int main()
  {
      int i;
      int *n=(int *)malloc(sizeof(int));
      n[0]=1;
      n[1]=2;
      n[2]=3;
      for(i=0;n[i];i++)
          printf("\n%d\n",n[i]);
  }
  </code></pre>
  
  <p>OUTPUT:</p>
  
  <pre><code>1
  
  2
  
  3
  
  135153
  </code></pre>
  
  <p>Even when I replace(in line 2 of the main block)</p>
  
  <pre><code>int *n=(int *)malloc(sizeof(int));
  </code></pre>
  
  <p>with</p>
  
  <pre><code>int *n=(int *)malloc(sizeof(int)*3);
  </code></pre>
  
  <p>the output is the same. What have I missed here?</p>
  
  <p>EDIT: Ok, so from what I've been able to understand, you can only have a condition like this when you're running through a string and not just any array, since arrays allocated using malloc() don't have a terminating character like \0.</p>