-1

I'm trying to create a 2-Dimensional array using malloc. My code seems correct but when I try to set values, I receive "Segmentation Fault" message.

#include <stdio.h>
#include <stdlib.h>

int main(){
    int i, j;
    int **m = (int **) malloc(5 * sizeof(int));

    if(m == NULL){
        printf("Error");
        getchar();
        exit(-1);
    }

    for(i = 0; i < 5; i++){
        m[i] = (int *) malloc(5 * sizeof(int));

        if(m[i] == NULL){
            printf("Error");
            getchar();
            exit(-1);
        }
    }

    for(i = 0; i < 5; i++){
        for(j = 0; j < 5; j++){
            printf("%d %d\n", i, j);
            m[i][j] = 0;
        }
    }

    for(i = 0; i < 5; i++){
        for(j = 0; j < 5; j++){
            printf("%d ", m[i][j]);
        }
        printf("\n");
    }

}

Thanks.

chrk
  • 4,037
  • 2
  • 39
  • 47

2 Answers2

1

Change

int **m = (int **) malloc(5 * sizeof(int));

to

//---------------------------------------v
int **m = (int **) malloc(5 * sizeof(int *));

Your code will fail where size of int is not equal to size of pointer variable.

Rohan
  • 52,392
  • 12
  • 90
  • 87
  • This could have been avoided by using the idiom `int **m = malloc(5 * sizeof *m);` – M.M Apr 07 '14 at 05:22
0

some systems might have pointer size not equal to size of int. In your case your assuming that pointer is of size int

int **m = (int **) malloc(5 * sizeof(int));

change it to

int **m = malloc(5 * sizeof(int *));

always free memory after use. it will lead to memory leak.

Also don't cast when using malloc Check here

Community
  • 1
  • 1
KARTHIK BHAT
  • 1,410
  • 13
  • 23