gpt4 book ai didi

c - 我什么时候可以检查指针的值

转载 作者:太空狗 更新时间:2023-10-29 15:26:42 26 4
gpt4 key购买 nike

好吧,最近我对这种事态感到惊讶: Evaluating the condition containing unitialized pointer - UB, but can it crash?

似乎是这样的:

int *p;
if(p != NULL)
{
int k;
}

理论上已经可以崩溃了。

我的问题是:什么时候检查指针的值是安全的?什么时候进行检查是安全的:if(ptr == SomeValue) - 这样它就不会触发 UB?

最佳答案

只有检查已初始化的自动变量的值才是安全的。指针也不异常(exception)。

这在 C.11 的 §6.3.2.1¶2 中有详细说明:

Except when it is the operand of the sizeof operator, the unary & operator, the ++ operator, the -- operator, or the left operand of the . operator or an assignment operator, an lvalue that does not have array type is converted to the value stored in the designated object (and is no longer an lvalue); this is called lvalue conversion. ... If the lvalue designates an object of automatic storage duration that could have been declared with the register storage class (never had its address taken), and that object is uninitialized (not declared with an initializer and no assignment to it has been performed prior to use), the behavior is undefined.

关于c - 我什么时候可以检查指针的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22472040/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com