title: Heap corruption while freeing allocated memory in C
body: <p>In an attempt to free up memory after a malloc command to prevent memory leaks, I am running into a heap corruption problem during runtime.  My debug is telling me that my application is trying to write to memory after the end of the heap buffer has been reached.  Here is what I have simplified to isolate my problem.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;math.h&gt;
  
  main(){
  
  int i,j,n;
  int temp[4];
  int **a;
  
  printf("Amount of intervals to be entered: ");
  scanf("%d", &amp;n);
  
  //allocate memory for a 2d array of size (n x 4)
  a = (int**) malloc(n*sizeof(int*));
  for (i=0;i&lt;4;i++){
      a[i] = (int*) malloc(4*sizeof(int));
  }
  
  if (!a){
      printf("malloc failed %d\n",__LINE__);
      exit(0);
  }
  
  printf("Please enter the intervals a line at a time followed by a return: \n");
  for(i=0;i&lt;n;i++){
      scanf("%d %d %d %d",&amp;a[i][0], &amp;a[i][1], &amp;a[i][2], &amp;a[i][3]);
  }
  
  for(i=0;i&lt;n;i++){
  
      printf("%d, %d, %d, %d\n", a[i][0], a[i][1], a[i][2], a[i][3]);
  
  }
  
  
  // free up the allocated memory 
  
  
  for (i=0;i&lt;n;i++){
      free(a[i]);
  }
  
  free(a);
  
  
  
  
  }
  </code></pre>
  
  <p>I'm not extremely familiar with allocating and de-allocating memory so I am at a loss as to what I should do.</p>