2

I have the next code which I want to read an 2D array. It does this, but after the program ends the program crashes every time. I have a bigger program, but here is the only problem. I have also read Correctly allocating multi-dimensional arrays and I debugged the program.

The question is: why does the program crash at the end even it throughout the expected operation procedure it works fine?

void dynamicMemAlloc(int n, int (**arrayPointer)[n][n]){
    *arrayPointer = malloc(sizeof(int[n][n]));
    assert(*arrayPointer != NULL);
}

void readMy2Darray(int n, int array[n][n]){
    int i, j;
    for(i = 1; i <= n; i++)
        for(j = 1; j <= n; j++)
            scanf("%d", &array[i][j]);
}
void printMy2Darray(int n, int array[n][n]){
    int i, j;
    for(i = 1; i <= n; i++){
        for(j = 1; j <= n; j++)
            printf("%d ", array[i][j]);
        printf("\n");
    }
}
int main(void){
    int n;
    printf("Read the dimension(n): ");
    scanf("%d", &n);
    int (*arrayPointer)[n][n];
    dynamicMemAlloc(n, &arrayPointer);
    printf("Read the 2D array:\n");
    readMy2Darray(n, *arrayPointer);
    printf("Printed array:\n");
    printMy2Darray(n, *arrayPointer);
    free(arrayPointer);
    return 0;
}

The error here

Community
  • 1
  • 1
Timʘtei
  • 753
  • 1
  • 8
  • 21

2 Answers2

6

In your code

for(i = 1; i <= n; i++)
        for(j = 1; j <= n; j++)

goes off by one. C arrays are 0-based indexed. You should have the loop condition set as

for(i = 0; i < n; i++)
        for(j = 0; j < n; j++) 

Otherwise, it causes undefined behavior.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

In this case, the fourth scanf will write past the end of the malloc()d array and likely overwrite the malloc() bookkeeping, making the free() call run into trouble.

But as specified in the other answer, all of this depends on undefined behaviour and will be implementation-specific.

marcolz
  • 2,880
  • 2
  • 23
  • 28