int *p;
{
int x = 0;
p = &x;
}
// p is no longer valid
{
int x = 0;
if (&x == p) {
*p = 2; // Is this valid?
}
}
在指向的对象被释放后访问指针是未定义的行为,但是如果稍后在同一区域发生一些分配,并且您显式地将旧指针与指向新对象的指针进行比较,会发生什么情况?如果我在比较它们之前将 &x
和 p
转换为 uintptr_t
会有影响吗?
(我知道不能保证两个 x
变量占据同一个位置。我没有理由这样做,但我可以想象,比方说,一个算法,你将一组指针相交可能已经用一组绝对有效的指针释放了,删除了过程中的无效指针。如果先前无效的指针等于已知的好指针,我很好奇会发生什么。)
最佳答案
根据我对标准(6.2.4.(2))的理解
The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.
比较时你有未定义的行为
if (&x == p) {
因为满足附件 J.2 中列出的这些要点:
— The value of a pointer to an object whose lifetime has ended is used (6.2.4).
— The value of an object with automatic storage duration is used while it is indeterminate (6.2.4, 6.7.9, 6.8).
关于c - 无效指针再次有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18383844/