I wrote a binary search function to avoid the following vulnerabilities (applicable to 32-bit machines ).
1: Unsigned int Len uses the unsigned int type to search for data larger than or equal to 2 GB.
2: Unsigned int LA = 0, He = len-1, mid; with the unsigned int type such in {mid = La + (HE-La)> 1 );} the statement can use displacement. {mid = (La + He)> 1 ;}is useless because (La + He) may cross the border, that is, greater than or equal to 4 GB.
3: Use if (mid = 0) return invalid_len; this is because if mid = La = He = 0, run He = mid-1; he = 4g-1
4: Return unsigned int type
# Include <stdio. h>
# Include <stdlib. h>
# Define invalid_len 0 xfffffffff
Unsigned int binsearch (int * P, unsigned int Len, int key)
{
If (P = NULL | Len = 0 | Len = invalid_len) return invalid_len;
Unsigned int LA = 0, He = len-1, mid = 0;
While (La <= He)
{
Mid = La + (HE-La)> 1 );
If (Key = P [Mid])
{
Return mid;
}
Else if (Key> P [Mid])
{
La = Mid + 1;
}
Else
{
If (mid = 0) return invalid_len;
He = mid-1;
}
}
Return invalid_len;
}
Int main (INT argc, char * argv [])
{
Const int Len = 100;
Int * P = (int *) malloc (LEN * sizeof (INT ));
If (P = NULL) Return-1;
Int I;
For (I = 0; I <Len; I ++) P [I] = I;
Printf ("% d/N", binsearch (p, Len, 0 ));
System ("pause ");
Return 0;
}