C compare pointers -
recently, wrote code compare pointers this:
if(p1+len < p2)
however, staff said should write this:
if(p2-p1 > len)
to safe. here,p1 , p2 char *
pointers,len integer. have no idea that.is right?
edit1: of course,p1 , p2 pointer same memory object @ begging.
edit2:just 1 min ago,i found bogo of question in code(about 3k lines),because len
big p1+len
can't store in 4 bytes of pointer,so p1+len < p2 true.but shouldn't in fact,so think should compare pointers in some situation:
if(p2 < p1 || (uint32_t)p2-p1 > (uint32_t)len)
in general, can safely compare pointers if they're both pointing parts of same memory object (or 1 position past end of object). when p1
, p1 + len
, , p2
conform rule, both of if
-tests equivalent, needn't worry. on other hand, if p1
, p2
known conform rule, , p1 + len
might far past end, if(p1-p2 > len)
safe. (but can't imagine that's case you. assume p1
points beginning of memory-block, , p1 + len
points position after end of it, right?)
what may have been thinking of integer arithmetic: if it's possible i1 + i2
overflow, know i3 - i1
not, i1 + i2 < i3
either wrap around (if they're unsigned integers) or trigger undefined behavior (if they're signed integers) or both (if system happens perform wraparound signed-integer overflow), whereas i3 - i1 > i2
not have problem.
edited add: in comment, write "len
value buff, may anything". in case, quite right, , p2 - p1 < len
safer, since p1 + len
may not valid.
Comments
Post a Comment