I am trying to make an arrangement with dynamic memory, 3-dimensional, my code is as follows:
typedef unsigned char matrix;
matrix ***mat(int n, int b)
{
    matrix ***temp = (matrix ***)malloc(n*sizeof(matrix**));
    for(int i=0; i<n; i++)
    {
        temp[i] = (matrix **)malloc(b*sizeof(matrix *));
        for(int j = 0; j < b; j++)
            temp[i][j]= (matrix *)malloc(b*sizeof(matrix));
    }
    return temp;
}
int main()
{ 
    matrix ***M2 = mat(3,2);
    for(int i=0; i<3; i++)
    {
        for(int j=0; j<2; j++)
        {
            for(int k=0; k<2; k++)
            {
                printf(" %d", M2[i][j][k]);
            }
            printf("\n");
        }
        printf("\n");
    }
    return 0;
}
when I run the program I have a segment violation, someone can tell me what the error is, since I can not visualize
 
     
     
    