問題描述
我正在學(xué)習(xí) C++ 并且我開始知道如果未初始化的指針可能指向內(nèi)存中的隨機(jī)位置并產(chǎn)生一些其他程序可能使用內(nèi)存的問題.
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.
現(xiàn)在如果是這種情況,我們不應(yīng)該在我們的代碼的任何部分中包含這一行:
Now if that is the case we should never have this line in any part of our code:
int* ptr;
相反,我們應(yīng)該有類似
Instead we should have something like
int* ptr = NULL; //Is this going to avoid the problem
請?zhí)岢鼋ㄗh,因?yàn)槲以诤芏鄷卸伎吹搅说谝恍?(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
這將導(dǎo)致 ptr
指向 NULL
,您可以將其明確檢查為默認(rèn)/未初始化值.它可以防止您描述的問題,但是粗心的程序員仍然可以在不檢查的情況下意外取消引用空指針,從而導(dǎo)致未定義的行為.
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.
主要優(yōu)點(diǎn)是您可以方便地檢查 ptr
是否已初始化為任何內(nèi)容,即:
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
}
因?yàn)檫@是非常慣用的,所以不將指針初始化為 NULL
是非常危險的.指針將被初始化為一個非 NULL 垃圾值,它并不真正指向任何真實(shí)的東西.最糟糕的是,上面的檢查會通過,如果碰巧指針中的地址是您可以合法訪問的內(nèi)存,則會導(dǎo)致更嚴(yán)重的問題.在某些嵌入式環(huán)境中,您可能能夠訪問內(nèi)存的任何部分,因此您可能會意外損壞內(nèi)存的隨機(jī)部分或執(zhí)行代碼的隨機(jī)部分.
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.
這篇關(guān)于代碼中的未初始化指針的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!