代码中未初始化的指针 [英] 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;
而是应该有
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
}
b $ b
由于这是很惯用的,它不会初始化 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.
这篇关于代码中未初始化的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!