0

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

Vasfed
  • 18,013
  • 10
  • 47
  • 53
BlackBox
  • 631
  • 1
  • 5
  • 19

1 Answers1

4

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.

Vasfed
  • 18,013
  • 10
  • 47
  • 53
  • he said that doesn't work in the comments, but I completely agree. On my 64-bit Mac sizeof pointers are 8 and sizeof ints are 4 – yano Mar 16 '16 at 21:05
  • @yano "it doesn't work" is not a useful problem description – M.M Mar 16 '16 at 21:23
  • I don't know exactly what I was doing wrong earlier not to make work that either, but now is going perfect. I realized the mistake. Unfortunately I was also issued by some recommendation of passing the matrix as return type and not as parameter. Even being (maybe) a better programming style for this job, that wasn't helping me to resolve this problem. Ty and cheers! – BlackBox Mar 16 '16 at 21:41
  • @M.M I agree... I assumed he meant he was still getting the seg fault with the `sizeof int` to `sizeof int*` change. No matter now, he only thought he was. – yano Mar 16 '16 at 23:05