如何比较C指针? [英] How to compare C pointers?

查看:57
本文介绍了如何比较C指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我编写了一些代码来比较类似这样的指针:

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)

为了安全起见. 在这里, p1 p2 char *指针, len 是整数. 我对此一无所知.对吗?

to be safe. Here,p1 and p2 are char * pointers,len is an integer. I have no idea about that.Is that right?

当然, p1 p2 指针在乞求时指向同一内存对象.

of course,p1 and p2 pointer to the same memory object at begging.

就在一分钟前,我在我的代码中找到了这个问题的 bogo (大约3K行),因为len太大,以致p1+len不能存储在4中指针的字节数,因此 p1 + len< p2 true .但这实际上不应该,因此,我认为我们应该在某些情况下比较这样的指针:

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)

推荐答案

通常,只有当指针都指向同一内存对象的各个部分(或指向对象末尾的一个位置)时,您才可以安全地比较指针.当p1p1 + lenp2都符合此规则时,两个if-测试都是等效的,因此您不必担心.另一方面,如果仅已知p1p2符合此规则,并且p1 + len可能远远超出结尾,则仅if(p2-p1 > len)是安全的. (但是我无法想象这是您的情况.我假设p1指向某个内存块的开头,而p1 + 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(p2-p1 > 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?)

他们可能一直在想的是整数算术:如果i1 + i2可能溢出,但您知道i3 - i1不会溢出,那么i1 + i2 < i3可能会回绕(如果它们是无符号整数)或触发未定义的行为(如果它们是带符号的整数)或两者(如果您的系统恰好执行有符号整数溢出的环绕操作),则i3 - i1 > i2不会出现此问题.

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.

编辑后添加:在注释中,您输入"len是buff中的值,因此可能是任何东西".在这种情况下,它们很正确,并且p2 - p1 > len更安全,因为p1 + len可能无效.

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.

这篇关于如何比较C指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆