Giorgos Mouch
Giorgos Mouch

Reputation: 70

Segmentation fault(core dumped) C

I am trying to make an X[N][M] array with malloc, and I am having this error. Can anybody help me with that ?

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

int main(int argc, char argv[])
{
  int N,M;  // N=megethos rows , M=megethos columns
  int **X;  // pinakas
  int size,i,j;


  printf("Give me the rows of the table: ");
  scanf("%d",&N);
  printf("Give me the columns: ");
  scanf("%d",&M);

  size = N*sizeof(int*);
  X = malloc(size);

  size = M * sizeof(int*);
  for(i=0; i<N;i++){
    X =malloc(size);
  }

  for(i=0;i<N;i++){
    for(j=0;j<M;j++){
      printf("Eisagwgh toy %d - %d stoixeioy: ",i+1,j+1);
      scanf("%d",&X[i][j]);
    }
  }

  for(i=0;i<N;i++){
    printf("\n");
    for(j=0;j<M;j++){
      printf("%d",X[i][j]);
    }
  }
  free(X);
}

I have already try to change this line: size = N*sizeof(int*); to this: size = N*sizeof(int); but still same error appear.

Upvotes: 0

Views: 64

Answers (2)

hanie
hanie

Reputation: 1885

I suggest this way of allocating memory:

    X = malloc(N * sizeof(int*));
    for (int i = 0; i < N; i++)
        X[i] = (int*)malloc(M * sizeof(int));

instead of this wrong allocating:

  size = N*sizeof(int*);
  X = malloc(size);

  size = M * sizeof(int*);
  for(i=0; i<N;i++){
    X =malloc(size);
  }

Upvotes: 0

SayAz
SayAz

Reputation: 760

Please see the below code, I just made a very small change in your code, must see the comment.

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char argv[])
{
  int N,M;  // N=megethos rows , M=megethos columns
  int **X;  // pinakas
  int size,i,j;


  printf("Give me the rows of the table: ");
  scanf("%d",&N);
  printf("Give me the columns: ");
  scanf("%d",&M);

  size = N*sizeof(int*);
  X = malloc(size);

  size = M * sizeof(int*);
  for(i=0; i<N;i++){
      //Here it intialize each row with size
    X[i] =malloc(size);
  }

  for(i=0;i<N;i++){
    for(j=0;j<M;j++){
      printf("Eisagwgh toy %d - %d stoixeioy: ",i+1,j+1);
      scanf("%d",&X[i][j]);
    }
  }

  for(i=0;i<N;i++){
    printf("\n");
    for(j=0;j<M;j++){
      printf("%d",X[i][j]);
    }
  }
  free(X);
}

Upvotes: 1

Related Questions