Uninitialized pointers in code(代码中的未初始化指针)
问题描述
我正在学习 C++ 并且我开始知道如果未初始化的指针可能指向内存中的随机位置并产生一些其他程序可能使用内存的问题.
I am learning C++ and I came to know that pointers if left uninitialized could point to random locations in memory and create problems that memory might be used by some other program.
现在如果是这种情况,我们不应该在我们的代码的任何部分中包含这一行:
Now if that is the case we should never have this line in any part of our code:
int* ptr;
相反,我们应该有类似
Instead we should have something like
int* ptr = NULL; //Is this going to avoid the problem
请提出建议,因为我在很多书中都看到了第一行 (int* ptr;
) 所以我有这个疑问.如果可能,还可以举一些例子.
Please suggest because I have seen the first line(int* ptr;
) in many books so I am getting this doubt. If possible give some examples also.
推荐答案
int* ptr = NULL; //Is this going to avoid the problem
这将导致 ptr
指向 NULL
,您可以将其明确检查为默认/未初始化值.它可以防止您描述的问题,但是粗心的程序员仍然可以在不检查的情况下意外取消引用空指针,从而导致未定义的行为.
This will cause ptr
to point to NULL
which you can explicitly check for as a default/uninitialized value. It prevents the problem you describe, but a careless programmer can still accidentally dereference a null pointer without checking, causing undefined behaviour.
主要优点是您可以方便地检查 ptr
是否已初始化为任何内容,即:
The main advantage is your convenience for checking whether the ptr
has or has not been initialized to anything, ie:
if (ptr != NULL)
{
// assume it points to something
}
因为这是非常惯用的,所以不将指针初始化为 NULL
是非常危险的.指针将被初始化为一个非 NULL 垃圾值,它并不真正指向任何真实的东西.最糟糕的是,上面的检查会通过,如果碰巧指针中的地址是您可以合法访问的内存,则会导致更严重的问题.在某些嵌入式环境中,您可能能够访问内存的任何部分,因此您可能会意外损坏内存的随机部分或执行代码的随机部分.
Since this is pretty idiomatic, its pretty dangerous to not initialize the pointer to NULL
. The pointer would be initialized to a non-NULL garbage value that doesn't really point to anything real. Worst of all, the check above would pass, causing even worse problems if it just so happens that the address in the pointer is memory you can legally access. In some Embedded environments, you might be able to access any part of memory, so you might accidentally corrupt random parts of memory or random parts of your executing code.
这篇关于代码中的未初始化指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:代码中的未初始化指针


基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01