Getting correct output while running but segmentation fault after submitting

#1

below is my code -

int Solution::searchMatrix(vector<vector > &A, int B) {

``````if(A[0][0]==B){
return 1;
}
``````

int n=A.size();
int m = A[0].size();
int x;
for(int i=0; i<n; i++){
if(B>=A[i][0] && B<=A[i][m-1]){
x=i;
break;
}
}
int s=0, e=m-1,mid;
while(s<=e){
mid = (int)(s+e)/2;
if(A[x][mid]==B){
return 1;
}
if(B>A[x][mid]){
s = mid+1;
}else if(B<A[x][mid]){
e = mid-1;
}
}

``````return 0;
``````

}

I am not able to figure out where am I making a mistake that I am getting a segmentation fault.

#2

When B is not inside matrix the code is suppose to return 0. But in your code when you check for B in for loop if B is not present then x takes garbage value hence gives seg fault when passed as index to vector.Try this small modification

int Solution::searchMatrix(vector<vector > &A, int B) {

``````int flag=0;                  //add this
if(A[0][0]==B){
return 1;
``````

}
int n=A.size();
int m = A[0].size();
int x;
for(int i=0; i<n; i++){
if(B>=A[i][0] && B<=A[i][m-1]){
x=i;
break;
}
}
{
return 0;
}
int s=0, e=m-1,mid;
while(s<=e){
mid = (int)(s+e)/2;
if(A[x][mid]==B){
return 1;
}
if(B>A[x][mid]){
s = mid+1;
}else if(B<A[x][mid]){
e = mid-1;
}
}

return 0;
}