M
Michael B Allen
I like to use limit pointers as sentinels when working on buffers
of data. Meaning I use ptr < lim where ptr and lim are both pointers
rather than n > 0 to determine if it is safe to proceed writing to that
location. The rationale is that it is simpler and thus safer because
you're not constantly recomputing integer n.
However, I've run into a case where this fails and I'd like to know what
the experts would do.
If I want to precompute if a pointer plus a length will exceed the limit
pointer I have a condition that can easily fail. There are two possible
expressions:
1) Add the length to the pointer and check to see if it exceeds the
limit like:
char *ptr, *lim;
int len;
if ((ptr + len) >= lim)
return -1;
This is not ok because len could be so large that the computed pointer
value becomes negative and the expression evaluates to false.
2) Compute the available space between the limit and pointer and compare
that to the required length:
if ((lim - ptr) =< len)
return -1;
This is also not ok because if lim is (char *)-1 and ptr is relatively
small, the computed space is still negative and thus the condition is
false. I'm not sure if this will happen on 32 bit platforms but on 64
bit it certainly can.
Note that I always also check to make sure lim != NULL and that ptr < lim.
So given any values for lim, ptr and len except lim != NULL and ptr <
lim, what expression would you use to safely ensure that ptr + len is
less than lim?
Mike
of data. Meaning I use ptr < lim where ptr and lim are both pointers
rather than n > 0 to determine if it is safe to proceed writing to that
location. The rationale is that it is simpler and thus safer because
you're not constantly recomputing integer n.
However, I've run into a case where this fails and I'd like to know what
the experts would do.
If I want to precompute if a pointer plus a length will exceed the limit
pointer I have a condition that can easily fail. There are two possible
expressions:
1) Add the length to the pointer and check to see if it exceeds the
limit like:
char *ptr, *lim;
int len;
if ((ptr + len) >= lim)
return -1;
This is not ok because len could be so large that the computed pointer
value becomes negative and the expression evaluates to false.
2) Compute the available space between the limit and pointer and compare
that to the required length:
if ((lim - ptr) =< len)
return -1;
This is also not ok because if lim is (char *)-1 and ptr is relatively
small, the computed space is still negative and thus the condition is
false. I'm not sure if this will happen on 32 bit platforms but on 64
bit it certainly can.
Note that I always also check to make sure lim != NULL and that ptr < lim.
So given any values for lim, ptr and len except lim != NULL and ptr <
lim, what expression would you use to safely ensure that ptr + len is
less than lim?
Mike