title: How to avoid SIGSEV Segmentation fault in C when allocating random elements to an int 2D matrix in a function?
body: <p>I am doing an assignment where we are required to assign random integers to a 5x5 matrix using array notation (so cannot use pointers here). After looking at <a href="https://stackoverflow.com/questions/13589248/generating-random-matrix-in-c">this</a> closed Stack Overflow non-question, I wrote the following newbie code:</p>
  
  <pre><code>#include&lt;stdio.h&gt;
  #include&lt;stdlib.h&gt;
  #include&lt;time.h&gt;
  
  #define rows 5
  #define cols 5
  
  void fillMatrix(int matrix[rows][cols])
  {
      srand(time(NULL));
      for(int i = 0; i&lt;rows; i++)
          for(int j = 0; i&lt;cols; j++)
              matrix[i][j] = rand() % 100 + 1;
  }
  
  int main()
  {
      int matrix[rows][cols];
      fillMatrix(matrix);
  }
  </code></pre>
  
  <p>The SIGSEGV Segmentation error happens in the line </p>
  
  <pre><code> matrix[i][j] = rand() % 100 + 1;
  </code></pre>
  
  <p>according to <code>gdb</code>.  Also, using <code>backtrace</code> I was able to see that this error arises from here:</p>
  
  <pre><code>(gdb) backtrace
  #0 0x0000000000400690 in fillMatrix (matrix=0x7fffffffe7d0) at program.c:13
  #1 0x00000000004006d2 in main () at program.c:19
  </code></pre>
  
  <p>My understanding is that the values being allocated are addressing memory locations which are not defined within the matrix, or are simply not allowed to be accessed. So considering <code>backtrace</code>, does this mean that the way I am declaring the matrix in the main function is wrong? Or is my function <code>fillMatrix()</code> itself wrong at the line in question?</p>
  
  <p>Thanks in advance!</p>