DerKaiser
DerKaiser

Reputation: 5

Segmentation Fault after 5th scanf

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]); 

 }`

Upvotes: 0

Views: 71

Answers (2)

pmg
pmg

Reputation: 108968

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

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

Try this

m = malloc(n * sizeof *m);

Upvotes: 4

SomethingSomething
SomethingSomething

Reputation: 12178

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*));

Upvotes: 0

Related Questions