Managing Dynamic Memory Is Error-Prone



昨天又借到了

可以繼續學習了!

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

The following three common program errors are associated with dynamic memory allocation:

  1. Failing to delete a pointer to dynamically allocated memory, thus preventing the memory from being returned to the free store. Failure to delete dynamically allocated memory is spoken of as a “memory leak.” Testing for memory leaks is difficult because they often do not appear until the application is run for a test period long enough to actually exhaust memory.

  2. Reading or writing to the object after it has been deleted. This error can sometimes be detected by setting the pointer to 0 after deleting the object to which the pointer had pointed.

  3. Applying a delete expression to the same memory location twice. This error can happen when two pointers address the same dynamically allocated object. If delete is applied to one of the pointers, then the object’s memory is returned to the free store. If we subsequently delete the second pointer, then the free store may be corrupted.

These kinds of errors in manipulating dynamically allocated memory are considerably easier to make than they are to track down and fix.』

中文版的是這樣說:『以下是三個與動態記憶體配置相關的常見錯誤:

1.未能將delete施行於指向動態配置記憶體的pointer身上,於是沒把記憶體歸還給自由空間。這便是所謂的「記憶體洩漏(memory leak),很難偵測出來,因為除非程式的測試時間長到得以耗盡記憶體,否則他們通常不會出現。

2.物件被刪除後,又對它進行讀取或寫入。這種錯誤有時可藉由「刪除pointer所指物件後把pointer設為0」而協助偵測出來。

3.對同一個記憶體位置施行delete算式兩次。這種錯誤有可能在兩個pointer指向同一個動態配置物時發生:當套用delete於其中一個pointer,該物件的記憶體就被歸還給自由空間。如果又施行delete於另一個pointer,自由空間就被「腐蝕」了。

找出以上錯誤並加以修復,遠比做出以上犯行困難多了。

確實沒錯,犯罪容易,悔改難。

Print Friendly, PDF & Email

發佈留言

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

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