Segmentation fault when filling a 2-d Jagged array <p>I am attempting to fill a jagged array with random values, where the columns and rows are determined by the user.</p> <p>The following code sometimes produces a segmentation fault. Why?</p> <pre><code>int main() { int row; int *col; int **ragArray; setupArray(ragArray, row, col); fillArray(ragArray, row, col); } void setupArray(int **&amp;ragArray, int &amp;row, int *&amp;col) { cout &lt;&lt; "Enter number of rows for the ragged array: "; cin &gt;&gt;row; int a; ragArray = (int**)malloc(row * sizeof(int*)); col = new int[row]; for (int i = 0; i &lt; row; i++) { cout &lt;&lt; "Enter number of columns for row " &lt;&lt; i + 1 &lt;&lt; ": "; cin &gt;&gt; a; col[i] = a; ragArray[i] = (int*)malloc(a * sizeof(int)); } } void fillArray(int **&amp;ragArray, int &amp;row, int *&amp;col) { for (int j = 0; j &lt; row; j++) { for (int i = 0; i &lt; col[j]; i++) { ragArray[i][j] = (rand()%9); } } } </code></pre> <p>This code produces a segmentation fault when I try to create an array with one row having a column greater than the amount of rows. For example, </p> <pre><code>Enter number of rows for the ragged array:5 Enter number of columns for row 1: 6 Enter number of columns for row 2: 2 Enter number of columns for row 3: 4 Enter number of columns for row 4: 1 Enter number of columns for row 5: 3 </code></pre> <p>produces a segfault when attempting to assign a value to <code>ragArray[0][5]</code>, however,</p> <pre><code>Enter number of rows for the ragged array:5 Enter number of columns for row 1: 5 Enter number of columns for row 2: 2 Enter number of columns for row 3: 4 Enter number of columns for row 4: 1 Enter number of columns for row 5: 3 </code></pre> <p>works just fine.</p>