Re: Promoting unsigned long int to long int
- From: jt@xxxxxxxxxxx (Jens Thoms Toerring)
- Date: 30 Jun 2008 12:07:04 GMT
pereges <Broli00@xxxxxxxxx> wrote:
Hello, I'm trying to sort an array of pointers based on the values
they point to. I'm using the quick sort method. The array of pointers
is parent_vpa and left, right represent the indices. The axis can take
value 0,1,2 and hence i decided to use unsigned char in order to save
some space. I noticed that the program fails and terminates abnormally
when I use left and right as unsigned long but works well when its
data type is declared as long. I would have preferred unsigned long
because the array indices should not be negative and in the calling
function unsigned integers (left = 0, right = n - 1) are passed. I
think the error occurs because of when there is exactly one element in
the array , the j-- can cause j to assume garbage values. My question
is am I breaking any rule or commiting some illegal action by passing
an unsigned long int as a parameter in calling function but using a
long int to receive the variable ? My compiler doesn't complain.
Using unsigned long should be completely ok.
#define ulong unsigned long int
#define uchar unsigned char
void quicksort(vector **parent_vpa, ulong left, ulong right, uchar
axis)
{
ulong i, j;
vector *pivotpoint;
vector *tempstore;
i = left;
j = right;
Lets look at the case you say seems to be the one where things
fail, left = right = 0. In that case i = j = 0
pivotpoint = parent_vpa[(left+right)/2];
Since i and j are equal you get into this loop.
while (i <= j)
{
The next two inner loops shouldn't do anything.
while (parent_vpa[i]->coord[axis] < pivotpoint->coord[axis])
{
i++;
}
while (parent_vpa[j]->coord[axis] > pivotpoint->coord[axis])
{
j--;
}
if (i <= j)
{
tempstore = parent_vpa[i];
parent_vpa[i] = parent_vpa[j];
parent_vpa[j] = tempstore;
This is useless if i == j.
i++;
Now i gets set to 1.
j--;
And j gets set to ULONG_MAX (unsigned integers "wrap around").
That will keep you in this loop for a loooong time and you will
try to access elements of your array that don't exist, rather
likely resulting in a crash.
}
}
if (left < j)
{
quicksort(parent_vpa, left, j, axis);
}
if (i < right)
{
quicksort(parent_vpa, i, right, axis);
}
return;
}
The simplest solution is to just bail out of the function if
left is equal to right - there's nothing to sort in that case.
Regards, Jens
--
\ Jens Thoms Toerring ___ jt@xxxxxxxxxxx
\__________________________ http://toerring.de
.
- Follow-Ups:
- Re: Promoting unsigned long int to long int
- From: pereges
- Re: Promoting unsigned long int to long int
- References:
- Promoting unsigned long int to long int
- From: pereges
- Promoting unsigned long int to long int
- Prev by Date: Re: How do you update a Makefile?
- Next by Date: Re: A tired question?
- Previous by thread: Re: Promoting unsigned long int to long int
- Next by thread: Re: Promoting unsigned long int to long int
- Index(es):
Relevant Pages
|