Ç比较指针 [英] C compare pointers
问题描述
最近,我写了一些code比较喜欢这个指针:
如果(P1 + LEN< P2)
然而,一些工作人员说,我应该写这样的:
如果(P2-P1> LEN)
是安全的。
在这里, P1 的和的 P2 的是的char *
指针的 LEN 的是一个整数。
我不知道that.Is想法,对吧?
EDIT1:当然的 P1 的和的 P2 的指针指向同一个内存对象在乞讨
EDIT2:只是一个小时前,我发现的 BOGO 的这个问题,在我的code(约3K线),因为 LEN
这么大, P1 + LEN
不能在4个字节的指针存储,这样的 P1 + LEN< P2 的是的真正的。但它不应该事实上,所以我认为我们应该在比较指针这样的某些情况下的:
如果(P2< P1 ||(uint32_t的)P2-P1>(uint32_t的)LEN)
在一般情况下,你只能比较安全的指针,如果他们都指向相同的内存对象的一部分(或过去的对象的结束一个位置) 。当 P1
, P1 + LEN
和 P2
均符合这一规则,无论你的,如果
-tests是等价的,所以你不用担心。在另一方面,如果只 P1
和 P2
已知符合此规则, P1 + LEN
可能是太远过去,最后,只有如果(P1-P2> LEN)
是安全的。 (但我无法想象这对你的情况,我认为 P1
指向一些内存块的开始,而 P1 + LEN
指向它的结束后的位置,对吧?)
什么他们可能一直在想的是整数运算:如果有可能的 I1 + I2
会溢出,但你知道, I3 - I1
不会,那么 I1 + I2< I3
既可以环绕(如果他们是无符号整数)或触发未定义的行为(如果他们有符号整数)或两个(如果你的系统中恰好有符号整数溢出执行回绕),而 I3 - I1> I2
不会有这个问题。
编辑补充:在一个评论,你写的 LEN
是浅黄色的值,因此它可能是任何东西。在这种情况下,他们是完全正确的,而 P2 - P1< LEN
更安全,因为 P1 + LEN
可能是无效的。
Recently, I wrote some code to compare pointers like this:
if(p1+len < p2)
however, some staff said that I should write like this:
if(p2-p1 > len)
to be safe.
Here,p1 and p2 are char *
pointers,len is an integer.
I have no idea about that.Is that right?
EDIT1: of course,p1 and p2 pointer to the same memory object at begging.
EDIT2:just one min ago,I found the bogo of this question in my code(about 3K lines),because len
is so big that p1+len
can't store in 4 bytes of pointer,so p1+len < p2 is true.But it shouldn't in fact,so I think we should compare pointers like this in some situation:
if(p2 < p1 || (uint32_t)p2-p1 > (uint32_t)len)
In general, you can only safely compare pointers if they're both pointing to parts of the same memory object (or one position past the end of the object). When p1
, p1 + len
, and p2
all conform to this rule, both of your if
-tests are equivalent, so you needn't worry. On the other hand, if only p1
and p2
are known to conform to this rule, and p1 + len
might be too far past the end, only if(p1-p2 > len)
is safe. (But I can't imagine that's the case for you. I assume that p1
points to the beginning of some memory-block, and p1 + len
points to the position after the end of it, right?)
What they may have been thinking of is integer arithmetic: if it's possible that i1 + i2
will overflow, but you know that i3 - i1
will not, then i1 + i2 < i3
could either wrap around (if they're unsigned integers) or trigger undefined behavior (if they're signed integers) or both (if your system happens to perform wraparound for signed-integer overflow), whereas i3 - i1 > i2
will not have that problem.
Edited to add: In a comment, you write "len
is a value from buff, so it may be anything". In that case, they are quite right, and p2 - p1 < len
is safer, since p1 + len
may not be valid.
这篇关于Ç比较指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!