# qsort problem when data is monotoneus - SCO

This is a discussion on qsort problem when data is monotoneus - SCO ; I have OSR507 MP3 with Development tools ver 5.2.0Aa I see that qsort core dumps when data array to be sorted has first few items of the same value. It is trying to go beyond number of elements in the ...

# Thread: qsort problem when data is monotoneus

1. ## qsort problem when data is monotoneus

I have OSR507 MP3 with Development tools ver 5.2.0Aa
I see that qsort core dumps when data array to be sorted has first few
items of the same value. It is trying to go beyond number of elements
in the array.

#include
#include
#define N 3
/*int a[N] = {15, 10, 11}; works just fine */
int a[N] = {10, 10, 11}; /* core dump */

int cmp_func(const void *i, const void *j)
{
int rc, *x = (int *)i, *y = (int *)j;

return(a[*x] < a[*y] ? 0 : 1);
}

int main(int argc, char *argv[])
{
int i, index[N];

for(i = 0; i < N; i++)
index[i] = i;
qsort(index, N, sizeof(int), cmp_func);
for(i = 0; i < N; i++)
printf("%i\n", a[index[i]]);
exit(0);
}
When I feed this routine 15, 10, 11 - everything is OK.
When given 10, 10, 11 - or any combination that of equal value - no
luck, it goes beyond 3 elements in the array.

Any clarification would be much appreciated.
Michael.

2. ## Re: qsort problem when data is monotoneus

On 20 May 2005 15:32:22 -0700, migurus@yahoo.com wrote:

> I see that qsort core dumps when data array to be sorted has first few
> items of the same value. It is trying to go beyond number of elements
> in the array.

More precisely, the use of qsort with an invalid comparison function
may result in core dump.

> int cmp_func(const void *i, const void *j)
> {
> int rc, *x = (int *)i, *y = (int *)j;
>
> return(a[*x] < a[*y] ? 0 : 1);
> }

Reread the spec for compar in the qsort man page. When will this ever
return a value less than zero?

Try replacing the body of that with something more like:

int a = *(int *) i;
int b = *(int *) j;
return a - b;