Rafiq Reefat Rafiq Reefat - 3 months ago 11
C Question

Why am I getting segmentation fault in this program?

#include<stdio.h>
int max_pairwise(int *array,int n) {
int result=0;
int i,j;

for(i=0; i<n; i++)
for(j=i+1; j<n; i++) {
if(array[i]*array[j]>result)
result=array[i]*array[j];
}
return result;
}

int main(void) {

int n;
scanf("%d",&n);

int array[n];
int i;
for(i=0; i<n; i++)
scanf("%d",&array[i]);


int result=max_pairwise(array,n);
printf("%d",result);

return 0;
}

Answer

You're incrementing the wrong variable in your inner loop:

//  here------v
for(j=i+1;j<n;i++)

As a result, i keeps getting incremented without bound. This results in reading off the end of the array, causing undefined behavior, with one of the possible symptoms being a segfault.

You want this:

for(j=i+1;j<n;j++)
Comments