P
P
Pinkman2020-05-17 03:30:38
C++ / C#
Pinkman, 2020-05-17 03:30:38

Where does the error come from?

Hello! I wrote a simple algorithm from a book in C.
Binary search algorithm.
But when I decided to check its performance, I met a strange error. If the value of the array length is more than 10,000 (well, the elements there also turn out to be from 1 to 10,000), then when I go beyond these values ​​(that is, I look for the number 10001 or -1 in the array), it starts to give an error: segmentation fault (core dumped). But when the value (and the length of the array and its contents) is up to 10,000, i.e. 1000 or 100, everything works as it should, and if the desired number is not found, then 0 is returned.
Found another error. If length = 2147483647, then the program refuses to work at all.

#include <stdio.h>
#include <stdlib.h>

const unsigned int length = 10000; 

int		binary_search(int *arr, int item)
{
  unsigned int low;
  unsigned int high;
  unsigned int mid;
  int			 guess;

  low = 0;
  high = length - 1;
  while (low <= high)
  {
    mid = high + low;
    guess = arr[mid];
    if (guess > item)
      high = mid - 1;
    else if (guess < item)
      low = mid - 1;
    if (guess == item)
      return (arr[mid]);
  }
  return (0);
}

int		main(int argc, char **argv)
{
  int arr[length];
  unsigned int count;

  count = 0;
  while (count < length)
  {
    arr[count] = count + 1;
    count++;
  }
  printf("%i", binary_search(arr, atoi(argv[1])));
  return (0);
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jcmvbkbc, 2020-05-17
@famousman204

mid = high + low;
guess = arr[mid];

The first obvious mistake here: the amount should be divided in half.
else if (guess < item)
  low = mid - 1;

The second obvious error is here: mid can be equal to 0, which means low can crawl out of the array from the bottom.
With the condition for exiting the search loop in the absence of the desired value in the array, not everything is OK either.
int arr[length];
If length = 2147483647, then the program refuses to work at all.

You are trying to allocate an 8GB array on the stack. As you can see, this is not a very good idea.

U
User700, 2020-05-17
@User700

int arr[length];

int		main(int argc, char **argv)
{
    ...
}

Declare the array as a global variable so that this memory is not on the stack. Or use malloc (+ free) to dynamically allocate it on the heap.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question