Search code examples
cpointerssegmentation-faultmalloc

Why a local variable is having value different from its assigned value?


The variable i is already having value 912 when the dimension of the matrix is 1x2 hence the program run into segmentation fault. I dont really understand what is the problem and why this is happening as the program runs fine when the size of the matrix is 3x3, 3x4, 2x2, etc.

#include <stdio.h>
#include <stdlib.h>

int *spiralOrder(int matrix[1][2], int matrixSize, int matrixColSize,
                 int *returnSize) {
    *returnSize = matrixSize * matrixColSize;
    int left = -1;
    int right = matrixColSize - 1;
    int top = 0;
    int bottom = matrixSize;
    int k = 0;
    int i = 0;
    int j = 0;
    int count = 0;
    int *list = (int *)calloc(*returnSize, sizeof(int));
    if (matrixSize == 1) {
        while (k < *returnSize) {
            list[k] = matrix[j][i];
            i++;
        }
        return list;
    }
    while (k < *returnSize) {
        printf(" ( (%d) %d %d %d %d %d %d) ",
               count++, j, i, left, right, top, bottom);
        if (i < right && j == top) {
            list[k] = matrix[j][i];
            i++;
        } else if (i == right && j < bottom) {
            if (j == top) {
                left++;
                bottom--;
            }
            list[k] = matrix[j][i];
            j++;
        } else if (j == bottom && i > left) {
            list[k] = matrix[j][i];
            i--;
        } else if (i == left && j > top) {
            if (j == bottom) {
                top++;
                right--;
            }
            list[k] = matrix[j][i];
            j--;
        }
        k++;
    }
    printf("\n");
    for (int i = 0; i < *returnSize; i++) {
        printf("at %i [%d]  \n", i, list[i]);
    }
    return list;
} 

int main() {
    int list[1][2] = {{ 1, 2 }};
    int size;
    spiralOrder(list, 1, 2, &size);
}

Solution

  • You make a special case if matrixSize is 1:

    if (matrixSize == 1) {
        while (k < *returnSize) {
            list[k] = matrix[j][i];
            i++;
        }
        return list;
    }
    

    The while loop is an infinite loop as k is not changed in the loop body. This leads to a buffer overflow with undefined behavior ultimately causing a segmentation fault.

    Using for loops with clear and consistent initialization, test and increment of the loop index is advisable to avoid such problems.