未检测到的空指针
Null pointer not detected
我是C 的新手。我期望两个指针没有指出任何被发现的指针。但是,这仅适用于其中一个。这些指针的物理地址有些不同-0xe00000001 vs 0x0(正确检测到该指针为空指针(。
我已经编写了以下代码片段:
#include <iostream>
using namespace std;
struct TNode {
TNode* Parent; // Pointer to the parent node
TNode* Left; // Pointer to the left child node
TNode* Right; // Pointer to the right child node
int Key; // Some data
};
int main() {
TNode parent;
parent.Key = 2;
TNode first;
first.Key = 1;
first.Parent = &parent;
parent.Left = &first;
cout << first.Left << endl; // get 0xe00000001 here
cout << first.Right <<endl; // get 0x0
if (first.Right == nullptr) {
cout <<"rnull"<<endl; // rnull
}
if (first.Left == nullptr) {
cout <<"lnull"<<endl; // nothing
}
return 0;
}
这里发生了什么?基本上,我想找到一种方法来检查第一个。左指向一无所有。
在您的示例中, first.Left
和 first.Right
是不可初学的, not null。这意味着它们在分配时基本上包含堆栈上的任何垃圾。访问实际值(例如,通过打印指针(实际上是未定义的行为,但是大多数编译器都在低优化设置上,它将仅打印该垃圾。
解决方案1:给成员变量默认值
如果您希望它们为null,则可以修改TNode
,以确保它们的初始值为null:
struct TNode {
TNode* Parent = nullptr;
TNode* Left = nullptr;
TNode* Right = nullptr;
int Key = 0;
};
int main() {
TNode n; //Everything initialized to null or 0
}
这将保证它们是无效的。
解决方案2:定义TNode()
初始化成员
另外,您也可以明确定义构造函数,使其使所有内容变为null
struct TNode {
TNode* Parent, Left, Right;
// Everything gets default-initialized to null
TNode() : Parent(), Left(), Right() {}
};
int main() {
Tnode n; // Everything initialized to nullptr or 0
}
解决方案3:在使用点默认initialize
即使您不明确定义构造函数,当您在声明该变量时将{}
显式初始化它时,所有内容都会初始化为0(或null,如果是指针(。
struct TNode {
TNode* Parent, Left, Right;
int Key;
};
int main() {
TNode iAmUninitialized; // This one is uninitialized
Tnode iAmInitialized{}; //This one has all it's members initialized to 0
}
首先,在C和C 中,没有一个指向指向的指针。无论指针中的价值如何,它都指向某物。甚至NULL也是一个解决" 0"的指针,但我们使用的指针表示代表零。一个非直接化的指针的问题在于,它可以指向任何事物,并且任何事物都可能是一个非法地址,它会导致例外或指向应用程序中的其他内容,如果修改了数据,则会导致不希望的侧面 - 效力。
在您的情况下,第二个指针为0x00,为空。但是,第一个指针是0x01,这不是null。
相关文章:
- 为什么会出现 gettnig 运行时错误:加载类型为"_Bit_type"(stl_bvector.h) 的空指针?
- 运行时错误:引用绑定到类型为"int"的空指针
- 这个失败的测试是将零添加到空指针未定义的行为、编译器错误还是其他什么?
- 为什么我在空指针错误(链表)中获取成员访问权限
- 从向量到空指针的 memcpy(反之亦然)不起作用
- 空指针常量 (nullptr)、空指针值和空成员指针值之间有什么区别?
- 成员访问是否在空指针上定义C++?
- 尝试将对象插入空指针数组时出现分段错误
- 为什么我们需要在 C++ 中检查空指针,而在 Java 中不需要?
- 是否允许向空指针添加零?
- 为什么 C 样式字符串的工作空指针检查不?
- 在函数内初始化无符号字符指针将返回空指针
- 为什么多维数组中的空字符串文本衰减为空指针?
- C++ 取消引用指向矢量的空指针时的分段错误
- 错误 C6011:取消引用空指针"NAME"。C++
- cppcheck取消引用空指针
- 打印空指针时,std::cout 可以打印 "NULL" 而不是 0 吗?
- 未检测到的空指针
- "空指针已通过",用于检测轮廓
- 为什么此循环不检测空指针?