Can't seem to figure out this segmentation fault and what's causing it. My sorting algo works fine for 100 generated numbers, but at some point things start to go awry. I'm adding 1 to a counter[] where the counter index is equal to the value at value[i].
void sort(int values[], int n)
{
int counter[65535];
for(int i = 0; i < n; i++)
{
// for each value in the array, record 1 at corresponding counter[] index
int j = values[i];
//eprintf("j is %i, and i is %i\n", j, i);
counter[j] += 1;
//eprintf("j is %i, and counter[j] is %i\n", j, counter[j]);
}
This is where values are reassigned back to values[] in order:
for(int i = 0; i < n; i++)
{
for(int j = 1; j < 65535; j++)
{
if (counter[j] > 0)
{
values[i] = j;
eprintf("counter[%i] is %i, values[%i] is %i\n", j, counter[j], i, values[i]);
counter[j] -= 1;
break;
}
}
}
return;
}
Here's what happens when piping in 200 values:
helpers.c:87: counter[59742] is 1, values[187] is 59742
helpers.c:87: counter[60545] is 1, values[188] is 60545
helpers.c:87: counter[62311] is 1, values[189] is 62311
helpers.c:87: counter[62558] is 1, values[190] is 62558
helpers.c:87: counter[62568] is 1569645408, values[191] is 62568
helpers.c:87: counter[62568] is 1569645407, values[192] is 62568
helpers.c:87: counter[62568] is 1569645406, values[193] is 62568
helpers.c:87: counter[62568] is 1569645405, values[194] is 62568
helpers.c:87: counter[62568] is 1569645404, values[195] is 62568
helpers.c:87: counter[62568] is 1569645403, values[196] is 62568
helpers.c:87: counter[62568] is 1569645402, values[197] is 62568
helpers.c:87: counter[62568] is 1569645401, values[198] is 62568
helpers.c:87: counter[62568] is 1569645400, values[199] is 62568
This bit is particularly confusing:
helpers.c:76: counter[62681] is 32766
Why would j increment to 32766 when presented with integer 62681 from the values[]?