评估包含未初始化指针的条件

编程入门 行业动态 更新时间:2024-10-17 17:18:05
本文介绍了评估包含未初始化指针的条件 - 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.

更多推荐

评估包含未初始化指针的条件

本文发布于:2023-07-28 02:31:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1226479.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:初始化   指针   条件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!