Uninitialized Variables Cause Run-Time Problems

C++ Primer 4/e 在變數這裡有一個警告:『

Using an uninitialized object is a common program error, and one that is often difficult to uncover. The compiler is not required to detect a use of an uninitialized variable, although many will warn about at least some uses of uninitialized variables. However, no compiler can detect all uses of uninitialized variables.

Sometimes, we’re lucky and using an uninitialized variable results in an immediate crash at run time. Once we track down the location of the crash, it is usually pretty easy to see that the variable was not properly initialized.

Other times, the program completes but produces erroneous results. Even worse, the results can appear correct when we run our program on one machine but fail on another. Adding code to the program in an unrelated location can cause what we thought was a correct program to suddenly start to produce incorrect results.

The problem is that uninitialized variables actually do have a value. The compiler puts the variable somewhere in memory and treats whatever bit pattern was in that memory as the variable’s initial state. When interpreted as an integral value, any bit pattern is a legitimate valuealthough the value is unlikely to be one that the programmer intended. Because the value is legal, using it is unlikely to lead to a crash. What it is likely to do is lead to incorrect execution and/or incorrect calculation.』

中文版的是這樣說:『使用未初始化物件是個常見的程式錯誤,也是很難發現的一種錯誤。編譯器並沒有要求偵測「未初始化變數的使用」。雖然很多編譯器會對某些未初始化變數的使用發出警告,然而沒有任何編譯器能夠偵測出所有未初始化變數的使用。

有時候我們很幸運地在使用一個未初始化變數時立刻於執行期當掉。只要追蹤崩潰點,通常很容易就可以發現變數未被適當初始化。

但很多時候程式順利執行,並產生錯誤結果。更糟的是在某一台機器上執行產生正確的結果,換到另一台卻出錯。如果急病亂投醫,在不相干位置加入程式碼,很可能造成原本正確的程式突然開始產生不正確的結果。

問題在於未初始化變數其實有一個值。編譯器首先把變數「放在」記憶體某處,然後把那塊記憶體的bit樣式(無論它是什麼)當作那個變數的初值。任何bit樣式(bit pattern)被當作整數來詮釋時都是合理的 – 雖然那不是程式員所希望得到的值。因為其值合法,所以使用他不太容易造成程式崩潰。比較可能的是導致不正確的執行和(或)不正確的計算結果。』

寫PHP的時候常常會不注意給初值,但也很少很錯誤,所以就會常忘記,特別是回來寫C 或C++就特別容易錯誤,這是一個很好的警告。

Print Friendly, PDF & Email

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料