Search code examples
cfor-loopmultidimensional-arraysegmentation-faultnested-loops

Unknown Segmentation fault Error while incrementing the index value in 2d array


There "Segmentation fault" error in the code.

int hourglassSum(int arr_rows, int arr_columns, int** arr) {
    int sum=0,max=0;
    for(int i=0; i<arr_columns;i++){
        for(int j=0; j<arr_rows;j++){
            sum = arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2];
            if(sum>max){
                max = sum;
            }
        }
    }
    return max;
}

I have done some debugging and I found that whenever I increment the 'i' that is 'i+1' and 'i+2' the error occurs. arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2];

This is the error

Program terminated with signal SIGSEGV, Segmentation fault.
#0  0x000000000040135a in hourglassSum (arr_rows=6, 
    arr_columns=<optimized out>, arr=<optimized out>) at Solution.c:33
33              if(sum>max){

Solution

  • In this statement

    sum = arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2];
    

    when i is equal to at least arr_columns - 2 and j is equal to at least arr_rows - 2 there is an access outside the arrays in expressions like arr[i+2][j] and arr[i][j+2] because the valid ranges of indices are [0, arr_rows ) and [0, arr_columns ).

    What you do is what you get.

    Also as the arrays are of the signed type int then the initial value of the variable max is incorrect

    int sum=0,max=0;
    

    The arrays for example can have all negative elements.

    Also if you indeed are passing to the function a two-dimensional array instead of an array of arrays then this parameter declaration

    int** arr
    

    is incorrect.

    In this case the function should be declared like

    int hourglassSum(int arr_rows, int arr_columns, int arr[][arr_columns]);