Why does a negative value give segmentation fault for the program which is to find pairs of value from the array which has the given sum?
#include <stdio.h>
void findpairs(int arr[], int arr_size, int sum)
{
int i, temp;
int hash[100] = {0};
for(i = 0; i < arr_size; i++)
{
temp = sum - arr[i];
if(hash[temp] == 1)
{
printf("Pair with given sum %d is (%d, %d) \n", sum, arr[i], temp);
}
hash[arr[i]] = 1;
}
}
int main()
{
int A[] = {4,-4,9,2,1,6,5,11};
int sum =7;
int arr_size = 8;
findpairs(A, arr_size, sum);
开发者_如何转开发return 0;
}
link to the same program
hash[arr[i]] = 1;
...
hash[-4] = 1;
Your hash
array has indices from 0 to 99, so you're accessing out-of-bounds data.
Your next out-of-bounds access will be for the value 9,
temp = 7 - 9;
if (hash[temp] == 1)
Because trying to access a negative index is bad.
temp = sum - arr[i];
if(hash[temp] == 1)
or
hash[arr[i]] = 1;
temp = sum - arr[i]
What if sum < arr [i]
? hash[temp] == 1
would segfault on most implementations.
Similar behaviour in case of hash[arr[i]] = 1;
if arr[i]
is negative.
Technically speaking accessing out of bound array element invokes Undefined Behaviour.
精彩评论