我聽說訪問值為 null 的指標是安全的,因為您沒有向它或從它設定任何資料,您只是在訪問它。
但我也聽說訪問它指向的內容(當它為空時)是不安全的,這是為什么呢?
如果您正在訪問它所指向的內容(當它為空時),您不是什么都沒有訪問嗎?
我認為這不應該有任何問題,除非您從中設定值。
我從很多人那里聽說過,但我從未經歷過任何與此相關的崩潰或錯誤(從空指標內部讀取資料時),當我發現例外時,我就讓它發生,因為我沒有設定任何資料從它到某事。那樣可以么?
int x;
int* px = &x;
int* pn = nullptr;
if (px==px) { do something;}
uj5u.com熱心網友回復:
通過訪問我的意思是取消參考
取消參考空指標是未定義的行為。
我從未經歷過任何與此相關的崩潰或錯誤
該程式具有未定義的行為,這意味著即使它沒有明確說明并且“似乎正在作業”,它仍然是錯誤的。
未定義的行為意味著任何事情1都可能發生,包括但不限于給出預期輸出的程式。但永遠不要依賴(或基于)具有未定義行為的程式的輸出。該程式可能會崩潰。
所以你看到的輸出(也許看到)是未定義行為的結果。正如我所說,不要依賴具有 UB 的程式的輸出。該程式可能會崩潰。
因此,使程式正確的第一步是洗掉 UB。只有這樣,您才能開始推理程式的輸出。
1有關未定義行為的更技術上準確的定義,請參見此處提到:對程式的行為沒有限制。
uj5u.com熱心網友回復:
示例代碼(此時由 OP 公開)有點令人困惑。
因此,我想在接受的答案中添加一些示例,什么是允許的,什么是不允許的:
#include <iostream>
int main()
{
int x = 0; // make some storage
int* px = &x; // px initalized with address of x -> OK.
int* pn = nullptr; // pn initialized with nullptr -> OK.
if (px == px) { /* ... */ } // senseless but -> OK.
if (px == pn) { /* ... */ } // -> OK.
std::cout << *px; // dereference a valid pointer -> OK.
std::cout << *pn; // dereference a null pointer -> UNDEFINED BEHAVIOR!
px = pn; // assign a (null) pointer -> OK.
std::cout << *px; // dereference a null pointer -> UNDEFINED BEHAVIOR!
// ...and finally a common bug...
int* py = nullptr; // -> OK.
{ int y = 1; // storage with limited life-time -> OK.
py = &y; // assign address of storage -> OK.
} // scope end -> life-time of y ends -> OK.
// Attention! This makes py dangling (pointing to released storage).
if (py /* != nullptr*/) { // This doesn't help. py is not a null pointer.
std::cout << *py; // access after end of life-time -> UNDEFINED BEHAVIOR!
}
}
編譯器的輸出(g 11.2):
g -std=c 17 -O2 -Wall -pedantic -pthread main.cpp # && ./a.out # Compile but don't exec. It contains UNDEFINED BEHAVIOR!
main.cpp: In function 'int main()':
main.cpp:8:10: warning: self-comparison always evaluates to true [-Wtautological-compare]
8 | if (px == px) { /* ... */ } // senseless but -> OK.
| ~~ ^~ ~~
關于大腸桿菌的演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/480155.html
上一篇:如何處理函式指標問題?
