代码中的未初始化指针 [英] Uninitialized pointers in code

查看:35
本文介绍了代码中的未初始化指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 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.

这篇关于代码中的未初始化指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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