某处在论坛上我遇到这样的:
Somewhere on the forums I encountered this:
Any attempt to evaluate an uninitialized pointer variable invokes undefined behavior. For example: int *ptr; /* uninitialized */ if (ptr == NULL) ...; /* undefined behavior */这是怎么意思?是不是意味着,如果我只写:
What is meant here? Is it meant that if I ONLY write:
if(ptr==NULL){int t;};这句话已经是UB?为什么?我不取消引用指针吧?(我在这种情况下,注意到有可能术语问题,通过UB,我提到:请问我的code崩溃JUST由于如果检查)
this statement is already UB? Why? I am not dereferencing the pointer right? (I noticed there maybe terminology issue, by UB in this case, I referred to: will my code crash JUST due to the if check?)
推荐答案的 是未初始化变量调用未定义行为的。没关系无论是指针或不
Using unitialized variables invokes undefined behavior. It doesn't matter whether it is pointer or not.
int i; int j = 7 * i;是不确定的为好。需要注意的是不确定的意思是什么都可能发生,包括一种可能性,预期它会工作。
is undefined as well. Note that "undefined" means that anything can happen, including a possibility that it will work as expected.
在您的情况:
int *ptr; if (ptr == NULL) { int i = 0; /* this line does nothing at all */ }PTR 可能包含任何东西,也可以是一些随机的垃圾,但它可以是 NULL 太。这code将最有可能不会崩溃,因为你只是比较 PTR 的价值 NULL 。我们不知道,如果执行进入状态的身体还是不行,我们不能肯定,甚至一些价值将是成功读取 - 因此,在的行为是未定义的。
ptr might contain anything, it can be some random trash, but it can be NULL too. This code will most likely not crash since you are just comparing value of ptr to NULL. We don't know if the execution enters the condition's body or not, we can't be even sure that some value will be successfully read - and therefore, the behavior is undefined.
更多推荐
评估包含未初始化指针的条件
发布评论