【正文】
檢測內(nèi)存訪問錯誤 我們 第一個例子是在動態(tài)內(nèi)存中分配一列,存取最后一個在數(shù)組序列外的元素,讀一個 未 定義 的數(shù)組元素,最終忘記分配這個數(shù)組。它說明不是所有的內(nèi)存調(diào)試器都能捕獲到同一個錯誤。源代碼編譯工具允許一個 BUG 發(fā)生的時候精確的找到代碼發(fā)生的位置。 非原始內(nèi)存 BUG 讀 非原始內(nèi)存是因?yàn)?C 或 C++允許創(chuàng)建變量在沒有一個原始值的情況下。新內(nèi)存被分配擔(dān)任起例如 malloc()和各種有程序員構(gòu)成的新的指針。 n0。 /* mem leak: A[] */ 14 } We pile the program with debug information and then run under Valgrind: gcc g valgrind tool=memcheck leakcheck=yes ./ In the following sections we go through the error list reported by Valgrind. Detecting an Invalid Write Access The first – and perhaps most severe – error is a buffer overrun: the accidental write access to array element A[100]. Because the array has only 100 elements, the highest valid index is 99. A[100] points to unallocated memory that is located just after the memory allocated for array A. Valgrind thus reports an “invalid write” error: ==11323== Invalid write of size 4 ==11323== at 0x8048518: main (:9) ==11323== Address 0x1BB261B8 is 0 bytes after a block ==11323== of size 400 alloc’d ==11323== at 0x1B903F40: malloc ==11323== (in /usr/lib/valgrind/) ==11323== by 0x80484F2: main (:6) The string ==11323== refers to the process ID and is useful when Valgrind is checking multiple processes 1. The important piece of information is that an invalid 1 Valgrind will, per default, check only the first (parent) process that has been invoked. Use option tracechildren=yes to check all child processes as well. Example 1: Detecting Memory Access Errors 37 write occurs in line 9 of . There is also additional information revealing the address of the closest allocated memory block and how it was allocated. The memory debugger guesses that the invalid write in line 9 is related to this memory block. The guess is correct because both belong to the same array A. Note that Valgrind is able to catch an outofarraybounds errors only when the array is allocated as dynamic memory with malloc() or new. This is the case in the example with the statement in line 6: 6 int* A = (int*)malloc( sizeof(int)*size )。 錯誤的內(nèi)存管 理用法 一 套 完整 BUG 集合 與錯誤聲明 對于內(nèi)存管理來說 :解除一個錯誤的內(nèi)存超過一次,在解除以后訪問內(nèi)存,或解除一個從分配過的阻塞內(nèi)存。他們建立內(nèi)存管理機(jī)制為一個被分配阻塞內(nèi)存利用不同的機(jī)制,并且確保是否每個阻塞內(nèi)存在最后都得到了分配。一次報告一個無用的寫錯誤。內(nèi)存調(diào)試器猜測第 9行與內(nèi)存阻塞有關(guān)。也有 Insure++, Valgrind,也有 BoundsChecker,除此之外的一些其他同類工具。 在內(nèi)存中令人討厭的事是內(nèi)存重載的時候 BUG 沒有被聲明。在一下的章節(jié),我們將描述幾個代表性的在 C或 C++程序中處理的內(nèi)容 BUG,介紹內(nèi)容調(diào)試器,并且介紹兩個內(nèi)存如何發(fā)現(xiàn) BUG 的例子。Fixing Memory Problems This chapter is about finding bugs in C/C++ programs with the help of a memory debugger. A