-3

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;
    }
}

2 Answers2

2

d+1 and q+1 both outside the boundary. Use d and q

If you want to initialize with zero use calloc() which is simple to use and reduces redundant operations

arr = (int **)malloc(d * sizeof(int *)); 
for (int u=0; u<d; u++) 
    scoreBoard[u] = (int *)calloc(q , sizeof(int)); 

This code will create 2d int array and initialize with zero

Raghav
  • 97
  • 1
  • 3
  • 11
1

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.

Isaiah
  • 685
  • 2
  • 15
  • 28