'C program to return a histogram can't proceed after asking for user input

The goal of the program is to return a histogram counting the number of occurrences of values in the data array which has num_elts members. However, it is stuck at collecting user input.

int *make_hist(int data[], int num_elts, int maxval) {
  int *hist = (int *)malloc(maxval * sizeof(int));
  int i = 0;
  while (i <= num_elts) {
    int val = data[i];
    if (val >= 0 && val <= maxval) {
      hist[val]++;
    }
  }
  return hist;
}

int main(void) {
  int values[20];
  printf("enter 20 integer values in the range 0-10\n");
  for (int i = 0; i < 20; i++) {
    scanf("%d", &values[i]);
  }
  int *result = make_hist(values, 20, 10);
  printf("occurrences:\n");

  for (int i = 0; i <= 10; i++) {
    printf("%d: %d\n", i, result[i]);
  }

  return 0;
}


Solution 1:[1]

You have an infinite loop in your int *make_hist(int data[], int num_elts, int maxval) function, in the while (i <= num_elts) section. You are not changing the value of i, and therefore i (0) will always be less then num_elets (20). I recommend adding ++i or i++ before the end of your while loop to update it.

int *make_hist(int data[], int num_elts, int maxval) {
     int *hist = (int *)malloc(maxval * sizeof(int));
     int i = 0;
     while (i <= num_elts) {
        int val = data[i];
        if (val >= 0 && val <= maxval) {
           hist[val]++;
        }
        ++i;
     }
     return hist;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jacob Glik