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 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 store. If we subsequently delete the second pointer, then the 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),很難偵測出來,因為除非程式的測試時間長到得以耗盡記憶體,否則他們通常不會出現。





Print Friendly, PDF & Email




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

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