无效的指针变得再次有效 [英] Invalid pointer becoming valid again
问题描述
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
变量占用相同的位置。我没有理由这样做,但我能想象,比方说,一个算法,其中你交了一组可能已经释放了一套绝对有效的指针的指针,在取出的过程中无效的指针。如果previously-无效指针等于已知的良好指针,我很好奇,会是什么发生的。)
(I know it's not guaranteed that the two x
variables occupy the same spot. I have no reason to do this, but I can imagine, say, an algorithm where you intersect a set of pointers that might have been freed with a set of definitely valid pointers, removing the invalid pointers in the process. If a previously-invalidated pointer is equal to a known good pointer, I'm curious what would happen.)
推荐答案
据我的标准的理解(6.2.4(2))
By my understanding of the standard (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.
你有当你比较不确定的行为
you have undefined behaviour when you compare
if (&x == p) {
因为这符合附件J.2列出以下几点:
as that meets these points listed in Annex J.2:
- 指针到一个对象,其生命周期结束时(6.2.4)的数值结果。
- 使用具有自动存储持续时间的对象的值,而这是不确定的(6.2.4,6.7.9,6.8)
— 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).
这篇关于无效的指针变得再次有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!