Reputation: 454
I'm trying to compare numerical values of two pointers with ">=" operator but instead of comparing them it adds some random values to the first.
void obj::Loader::calculate_size(const char* start_ptr, const char* end_ptr, atomic_long& v, atomic_long& vt, atomic_long& vn, atomic_long& f) {
while (start_ptr >= end_ptr) {
if (*start_ptr == 'v') {
start_ptr++;
if (*start_ptr == ' ') {
v++;
start_ptr += 27;
}
else if (*start_ptr == 't') {
vt++;
start_ptr += 18;
}
else if (*start_ptr == 'n') {
vn++;
start_ptr += 21;
}
}
else if (*start_ptr == 'f') {
start_ptr++;
if (*start_ptr == ' ') {
f += 3;
start_ptr += 17;
}
}
start_ptr++;
}
}
This function is supposed to count all instances of these letters in a part of a memory-mapped file (from "start_ptr" to "end_ptr"). Knowing the minimal length at certain portions of the file I decided to increment the "start_ptr" by more than one sometimes but by doing that I can't rely on "!=" operator to stop the loop.
The problem is ">=" doesn't really work as it would on integers and it just crashes the whole thing. Are there any alternatives?
Upvotes: 0
Views: 60
Reputation: 4673
The comparison looks to be wrong to me: instead of
while (start_ptr >= end_ptr) {
// [...]
start_ptr++;
}
I would expect the natural condition to be:
while (start_ptr < end_ptr) {
// [...]
start_ptr++;
}
I suspect the crash in your program is not due to the pointer comparison directly, but is a side effect of something unexpected that happens when the loop is not entered.
Upvotes: 1
Reputation: 238391
Given that the loop condition is start_ptr >= end_ptr
, and considering that the loop body only ever increments start_ptr
, if the loop is ever entered, then start_ptr
can never become smaller than end_ptr
and therefore the loop is infinite. The behaviour of the program is undefined.
It would be rather unconventional for "start" to be after the end, so I suspect that this is a mistake in the logic.
Upvotes: 2