解引用NULL指针的哪些部分会导致不良行为? [英] What part of dereferencing NULL pointers causes undesired behavior?

查看:977
本文介绍了解引用NULL指针的哪些部分会导致不良行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇,解引用一个NULL ptr的什么部分导致不良行为。示例:

I am curious as to what part of the dereferencing a NULL ptr causes undesired behavior. Example:

//  #1
someObj * a;
a = NULL;
(*a).somefunc();   // crash, dereferenced a null ptr and called one of its function
                   // same as a->somefunc();

//  #2
someObj * b;
anotherObj * c;
b = NULL;
c->anotherfunc(*b);   // dereferenced the ptr, but didn't call one of it's functions

这里我们看到#2我实际上没有尝试访问数据或b中的函数,所以如果* b只是解析为NULL,我们将NULL传递给anotherfunc()?这仍然会导致不良的行为?

Here we see in #2 that I didn't actually try to access data or a function out of b, so would this still cause undesired behavior if *b just resolves to NULL and we're passing NULL into anotherfunc() ?

推荐答案

在标准中有一个空指针值的概念。这是一个不同的值,当程序尝试通过它访问内存时导致未定义的行为。在实践中,许多现代实现使程序崩溃,这是有用的行为。毕竟,这样的尝试是错误的。

There is a concept, in the standard, of a null pointer value. This is a distinct value that causes undefined behavior when the program attempts to access memory through it. In practice, lots of modern implementations have it crash the program, which is useful behavior. After all, such an attempt is a mistake.

空指针值的名称是 0 在指针上下文中的其他常量积分表达式(例如 3 - 3 )。还有一个 NULL 宏,它必须在C ++中求值为0,但可以(void *)0 C(C ++更坚持指针是类型安全的)。在C ++ 0x中,将有一个名为 nullptr 的显式值,最后给空指针一个显式名称。

The name of the null pointer value is 0, or any other constant integral expression in pointer context (like 3 - 3, for example). There is also a NULL macro, which has to evaluate to 0 in C++ but can be (void *)0 in C (C++ insists more on pointers being type-safe). In C++0x, there will be an explicit value called nullptr, finally giving the null pointer an explicit name.

null指针的值不一定是一个实际的零,虽然它是在我所知道的所有实现,并且没有工作的奇数计算机已经大部分已经退休。

The value of the null pointer doesn't have to be an actual zero, although it is on all implementations I'm aware of, and the odd computers where that didn't work have mostly been retired.

你错误的说明了你最后一个例子中发生了什么。 * b 无法解析为任何内容。传递 * b 是未定义的行为,这意味着实现可以做任何它喜欢它。它可以或可以不被标记为错误,并且可以或可以不导致问题。

You're misstating what happens in your last example. *b doesn't resolve into anything. Passing *b is undefined behavior, which means the implementation can do anything it likes with it. It may or may not be flagged as an error, and may or may not cause problems. The behavior can change for no apparent reason, and so doing this is a mistake.

如果一个被调用的函数期望一个指针值,传递一个空指针值就是完美的合法,被调用的函数应该正确处理它。取消引用空指针值永远不合法。

If a called function is expecting a pointer value, passing it a null pointer value is perfectly legitimate, and the called function should handle it properly. Dereferencing a null pointer value is never legitimate.

这篇关于解引用NULL指针的哪些部分会导致不良行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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