评估包含未初始化指针的条件 - UB,但它会崩溃? [英] Evaluating the condition containing unitialized pointer - UB, but can it crash?

查看:168
本文介绍了评估包含未初始化指针的条件 - UB,但它会崩溃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

某处在论坛上我遇到这样的:

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.

这篇关于评估包含未初始化指针的条件 - UB,但它会崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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