Reputation: 1
I need to know the output of the following c function
bool GC_search_memaddr (void* high_add, void* low_add, void* search_add)
{
void ** gc_ptr_to_ptr;
void * gc_temp;
gc_temp = high_add;
while( gc_temp > low_add )
{
gc_temp = gc_temp - 1;
gc_ptr_to_ptr = (void**)gc_temp;
if ((*gc_ptr_to_ptr) == search_add)
return True;
}
return False;
}
In this all 3 of the input functions are pointers. I thought that this was just a simple increment based search function but the problem is that if you change all of them to int the output of the function changes sometimes. Can anybody tell what exactly is happening here ...
Upvotes: -1
Views: 207
Reputation: 239301
As blastfurnace
says, it's searching byte-by-byte for a supplied pointer value. The int
equivalent would be:
bool GC_search_memaddr (void* high_add, void* low_add, int search_add)
{
int * gc_ptr_to_int;
void * gc_temp;
gc_temp = high_add;
while( gc_temp > low_add )
{
gc_temp = gc_temp - 1;
gc_ptr_to_int = (int *)gc_temp;
if ((*gc_ptr_to_int) == search_add)
return True;
}
return False;
}
Though, gc_temp
should actually be of type char *
, and it should be using memcpy()
to account for endianness issues, so it should really look like:
bool GC_search_memaddr (void* high_add, void* low_add, void *search_add)
{
void *gc_ptr;
char *gc_temp = high_add;
while (gc_temp > low_add)
{
gc_temp--;
memcpy(&gc_ptr, gc_temp, sizeof gc_ptr);
if (gc_ptr == search_add)
return True;
}
return False;
}
Upvotes: 1
Reputation: 18652
The variables low_add
and high_add
contain the start and end addresses of a region of memory. The function searches that region of memory for a pointer that contains the same value that's in search_add
. From the function name I'm assuming it's part of some garbage collector.
Upvotes: 2
Reputation: 59841
The function seems to determine if the address search_add is between the addresses high_add and low_add. Why this isn't done with pointer subtraction and why there is the ugly cast to void**
just to dereference it on the next possible occasion is beyond me.
Upvotes: 0
Reputation: 225132
Pointer arithmetic is likely your problem. The line:
gc_temp = gc_temp - 1;
is going to change the value of gc_temp
by whatever your compiler decides sizeof(void)
is. If you change the parameters and local variables to int
, they will iterate by exactly 1
. Break out your debugger and see what's going on.
Upvotes: 3