title: Segmentation fault at the end of the C program
body: <p>Is the segmentation fault at the end of the code (just to allocate memory to 2D array and print the result)? The last <code>printf</code> statement is being printed and any code that I add at the end runs successfully and then segfault appears.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  int main(void)
  {
      int n,i,j,**mat;
  
      printf("\nEnter the size of the square matrix: ");
      scanf("%d",&amp;n);
  
      *mat = (int **)malloc(n*sizeof(int *)); 
  
      for(i=0;i&lt;n;i++)
      {
        mat[i]= (int *)malloc(n*sizeof(int));
      }
  
      for(i=0;i&lt;n;i++)
      {
        for(j=0;j&lt;n;j++) printf("%d\t",mat[i][j]=rand()%10*i+j);
        printf("\n\n\n");
      }
  
      printf("Bye\n");
      return 0;
  }
  </code></pre>
  
  <p>Technically <code>*mat</code> in 8th line (printed in code) should be <code>mat</code>, but then everything is fine. The code mentioned compiles (with obvious warning of incompatible pointer type in gcc) and works except at the end when it prints segfault.
  Had there been a segfault in the program, it wouldn't had run till the end!</p>