C language, binary lookup, corrected version, vulnerability, binary method, 32-bit

Source: Internet
Author: User

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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.