0

This code gives a Segmentation Fault at the exact 5th line of input. If n<5 or in the debugger everything is fine.

scanf("%d %d",&n,&x);
m=(int**)malloc(n*sizeof(int));
for(i=0;i<n;i++)
{
     m[i]=(int*)malloc(2*sizeof(int));
 }

 for(i=0;i<n;i++)
{
  scanf("%d %d",&m[i][0],&m[i][1]); 

 }`
DerKaiser
  • 5
  • 2

2 Answers2

4

assumes sizeof (int) and sizeof (int*) are the same

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

Try this

m = malloc(n * sizeof *m);
pmg
  • 106,608
  • 13
  • 126
  • 198
0

Your mistake: You allocate memory for ints while you need int pointers

(As your m array is going to hold pointers for other int arrays)

mistake:

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

correct:

m=(int**)malloc(n*sizeof(int*));
SomethingSomething
  • 11,491
  • 17
  • 68
  • 126