BlackBox
BlackBox

Reputation: 643

Segmentation Fault: 11 when allocating a matrix

I get segmentation fault when using an allocated matrix and I don't understand why. This code currently works and doesn't work dependently from the computer

#include <stdlib.h>

void allocMatrix(int ***M, int n, int m) {
    *M = (int**)malloc(n * sizeof(int));
    int i = 0;
    while(i<n) {
        (*M)[i] = malloc(m * sizeof(int));
        i++;
    }
}


int main(void) {
    int **mat;

    int R, C;
    R = 15;
    C = 10;
    allocMatrix(&mat, R, C);
    int i,j;
    for(i = 0; i < R; i++) {
        for( j = 0; j < C; j++) {
             *(*(mat+i)+j) = j+i*R;
        }
    }
#ifdef WIN32
    system("pause");
#endif
}

I get segmentation fault: 11 or EXC BAD ACCESS in Xcode. As said, happens only to some computers

Upvotes: 1

Views: 191

Answers (1)

Vasfed
Vasfed

Reputation: 18444

sizeof(int) is not guaranteed to be equal to sizeof(int*), so your allocated memory block is very likely to be too small. Writing to unallocated memory is undefined behaviour, sometimes it may work as expected, sometimes not.

Upvotes: 4

Related Questions