錯誤: heap-use-after-free
位址清理程式錯誤:使用已解除配置的記憶體
我們示範三個範例,其中堆積中的儲存體可以透過 malloc
、 realloc
(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。
產生的錯誤
擲回的例外狀況對話方塊會指向第 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
擲回的例外狀況對話方塊指向第 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
擲回的例外狀況對話方塊指向第 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
擲回的例外狀況對話方塊會指向第 12 行*x = 42,並說: 位址清理程式錯誤:使用已解除配置的記憶體。 螢幕擷取畫面中未顯示顯示記憶體位址的主控台視窗中的輸出,以及識別可定址位元組的索引鍵、堆積留下紅色區域位元組,以及錯誤區域中某些可定址和部分可定址的位元組。
另請參閱
AddressSanitizer 概觀
AddressSanitizer 已知問題
AddressSanitizer 組建和語言參考
AddressSanitizer 執行時間參考
AddressSanitizer 陰影位元組
AddressSanitizer 雲端或分散式測試
AddressSanitizer 偵錯工具整合
AddressSanitizer 錯誤範例
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應