简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM