0

My program got a problem when I used this command './generate 1000 50 | ./find 127' which generating random number to run it. It shows "Segmentation fault", but it works fine when I type the input numbers individually. Could you help me what I make a mistake on the program?

Here is my helpers.c code. Thank you.

#include <cs50.h>
#include <stdio.h>

#include "helpers.h"

/**
 * Returns true if value is in array of n values, else false.
 */

bool search(int value, int values[], int n)
{
    int t = 0, start = 0, end = n - 1, size = 1;
    do
    {
        size = end - start;
        int middle = (start + end) / 2;
        if(value == values[middle])
        {
            t = 1;
            break;
        }
        else if(value > values[middle])
        {
            start = middle + 1;
        }
        else if(value < values[middle])
        {
            end = middle - 1;
        }
    }
    while(size >= 1);
    return (t);
}


/**
 * Sorts array of n values.
 */

void sort(int values[], int n)
{
    const int MAX = 65536;
    // integer counting array and maximum length of the array
    int count[MAX], count_MAX = values[0];
    // get a number to counting array
    for(int j = 0; j < n; j++)
    {
        count[values[j]]++;
        // find maximum count array
        if(values[j] > count_MAX)
        {
            count_MAX = values[j];
        }
    }
    // sorting counter
    int x = 0;

    // check counting array
    for(int k = 0; k <= count_MAX; k++)
    {
        // have this input number?
        if(count[k] > 0)
        {
            // how many does it have in this number?
            for(int m = 0; m < count[k]; m++)
            {
                //ordered number by using counting sort
                values[x] = k;
                x++;
            }
        }
    }
}
0

For search, imagine an array [43], and searching for 42.

You'd start at start = 0 end = 1, and in the loop do size = 1 middle = 0, and since 42<43, end = -1

As size >= 1, you keep looping.

Next iteration, it's size = -1 middle = -1 AND BAM! values[-1] is not in the array, even though the interval bounds adjustment looks correct.

A do..while is a bad idea here, as it would for example not prevent you from accessing an element in an empty array. I used a while loop instead, with while (start <= end).

In sort, you don't initialise count. You should, for example using int count[MAX] = {0}. Otherwise, the initial content of count is often all-zeroes, but generally undefined.

The if(count[k] > 0) is unnecessary, as it's implied in the for loop's condition.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .