Search code examples
carrayspointerssegmentation-faultdouble-pointer

Segmentation fault when initializing 2D array in c


I am declaring a 2d array in a headers file like this : int **arr; Then I'm allocating memory and I initialize it with zeros. However I'm getting segmentation fault.

Here is my code :

arr = (int **)malloc(d * sizeof(int *)); 
for (int u=0; u<d; u++) 
    arr[u] = (int *)malloc(q * sizeof(int)); 
for(int i=0; i<d+1; i++)
{
    for(int j=0; j<q+1; j++)
    {
        arr[i][j]=0;
    }
}

Solution

  • You are getting a segmentation fault because you are overstepping the array's bounds.

    for (int i = 0; i < d + 1; i++)
    

    Should become:

    for (int i = 0; i < d; i++)
    

    And similarly for the other one. Don't forget array indices go from 0 to 1 less than the size (in elements) of the array.

    Also:

    Was the memory for scoreboard allocated? Currently, you create an array called arr rather than for the scoreboard you are initializing, so scoreboard[u] may also be out of bounds regardless of the value of u.