共用方式為


錯誤: heap-use-after-free

位址清理程序錯誤:使用已解除分配的記憶體

我們示範三個範例,其中堆積中的記憶體可以透過 mallocrealloc (C) 和 new (C++) 設定,以及錯誤地使用 volatile

例- malloc

// example1.cpp
// heap-use-after-free error
#include <stdlib.h>

int main() {
  char *x = (char*)malloc(10 * sizeof(char));
  free(x);

  // ...

  return x[5];   // Boom!
}

若要建置及測試此範例,請在Visual Studio 2019 16.9版或更新版本的 開發人員命令提示字元中執行下列命令:

cl example1.cpp /fsanitize=address /Zi
devenv /debugexe example1.exe

當 Visual Studio 出現時,請按 F5 以執行範例 1。

產生的錯誤

調試程式的螢幕快照,其中顯示使用已解除分配的記憶體錯誤,例如 1。

擲回的例外狀況對話框會指向第 11 行,傳回 x [ 5 ],並說: 位址清理器錯誤使用已解除分配的記憶體。 螢幕快照中未顯示顯示記憶體位址的控制台視窗中的輸出,以及識別可尋址位元組、部分可尋址位元組、釋放堆積區域,以及錯誤區域中留下紅色區域位元組的索引鍵。

例- operator new

// example2.cpp
// heap-use-after-free error
#include <windows.h>

int main() {
  char *buffer = new char[42];
  delete [] buffer;

  // ...

  buffer[0] = 42;  // Boom!
  return 0;
}

若要建置及測試此範例,請在Visual Studio 2019 16.9版或更新版本的 開發人員命令提示字元中執行下列命令:

cl example2.cpp /fsanitize=address /Zi
devenv /debugexe example2.exe

當 Visual Studio 出現時,請按 F5 以執行範例 2。

產生的錯誤 - 運算子 new

調試程式的螢幕快照,其中顯示範例 2 中使用解除分配的記憶體錯誤。

擲回的例外狀況對話框指向第 11 行 buffer[0] = 42,並說: Address Sanitizer Error: Use of deallocated memory. 螢幕快照中未顯示顯示記憶體位址的控制台視窗中的輸出,以及識別可尋址位元組、部分可尋址位元組、釋放堆積區域和堆積的索引鍵,會在錯誤的區域中留下alloca紅色區域位元組。

例- realloc

// example3.cpp
// heap-use-after-free error
#include <malloc.h>

int main() {
  char *buffer = (char*)realloc(0, 42);
  free(buffer);

  // ...

  buffer[0] = 42;  // Boom!
  return 0;
}

若要建置及測試此範例,請在Visual Studio 2019 16.9版或更新版本的 開發人員命令提示字元中執行下列命令:

cl example3.cpp /fsanitize=address /Zi
devenv /debugexe example3.exe

當 Visual Studio 出現時,請按 F5 以執行範例 3。

產生的錯誤 - realloc

調試程式的螢幕快照,其中顯示範例 3 中使用已解除分配的記憶體錯誤。

擲回的例外狀況對話框指向第 11 行 buffer[0] = 42,並說: Address Sanitizer Error: Use of deallocated memory. 螢幕快照中未顯示顯示記憶體位址的控制台視窗中的輸出,以及識別可尋址位元組、部分可尋址位元組、釋放堆積區域,以及錯誤區域中留下紅色區域位元組的索引鍵。

範例 - volatile

// example4.cpp
// heap-use-after-free error
#include <stdlib.h>

int main() {

  volatile char *x = (char*)malloc(sizeof(char));
  free((void*)x);

      //...

  *x = 42;        // Boom!
}

若要建置及測試此範例,請在Visual Studio 2019 16.9版或更新版本的 開發人員命令提示字元中執行下列命令:

cl example4.cpp /fsanitize=address /Zi
devenv /debugexe example4.exe

當 Visual Studio 出現時,請按 F5 以執行範例 4。

產生的錯誤 - volatile

調試程式的螢幕快照,其中顯示範例 4 中使用已解除分配的記憶體錯誤。

擲回的例外狀況對話框會指向第 12 行*x = 42,並說: 位址清理程序錯誤:使用已解除分配的記憶體。 螢幕快照中未顯示顯示記憶體位址的控制台視窗中的輸出,以及識別可尋址位元組的索引鍵、堆積留下紅色區域位元組,以及錯誤區域中某些可尋址和部分可尋址的位元組。

另請參閱

AddressSanitizer 概觀
AddressSanitizer 已知問題
AddressSanitizer 組建和語言參考
AddressSanitizer 運行時間參考
AddressSanitizer 陰影位元組
AddressSanitizer 雲端或分散式測試
AddressSanitizer 調試程式整合
AddressSanitizer 錯誤範例