錯誤: dynamic-stack-buffer-overflow
位址清理程式錯誤:dynamic-stack-buffer-overflow
此範例顯示從堆疊配置物件界限外的緩衝區存取所產生的錯誤。
範例 - alloca
溢位(右)
// example1.cpp
// dynamic-stack-buffer-overflow error
#include <malloc.h>
__declspec(noinline)
void foo(int index, int len) {
volatile char *str = (volatile char *)_alloca(len);
// reinterpret_cast<long>(str) & 31L;
str[index] = '1'; // Boom !
}
int main(int argc, char **argv) {
foo(33, 10);
return 0;
}
若要建置及測試此範例,請在Visual Studio 2019 16.9版或更新版本的 開發人員命令提示字元中執行下列命令:
cl example1.cpp /fsanitize=address /Zi
devenv /debugexe example1.exe
產生的錯誤
範例 - alloca
溢位(左)
// example2.cpp
// dynamic-stack-buffer-overflow error
#include <malloc.h>
__declspec(noinline)
void foo(int index, int len) {
volatile char *str = (volatile char *)_alloca(len);
str[index] = '1'; // Boom!
}
int main(int argc, char **argv) {
foo(-1, 10);
return 0;
}
若要建置及測試此範例,請在Visual Studio 2019 16.9版或更新版本的 開發人員命令提示字元中執行下列命令:
cl example2.cpp /fsanitize=address /Zi
devenv /debugexe example2.exe
產生的錯誤 ─ alloca
溢位 (左)
範例 - 對 的數個呼叫 alloca
// example3.cpp
// dynamic-stack-buffer-overflow error
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define SIZE 7
extern void nothing();
int x=13,*aa,*bb,y=0;
int fail = 0;
int tmp;
int main()
{
int* cc;
int i;
int k = 17;
__try {
tmp = k;
aa = (int*)_alloca(SIZE * sizeof(int));
if (((int)aa) & 0x3)
fail = 1;
for (i = 0; i < SIZE; i++) {
aa[i] = x + 1 + i;
}
bb = (int*)_alloca(x * sizeof(int));
if (((int)bb) & 0x3)
fail = 1;
for (i = 0; i < x; i++) {
bb[i] = 7;
bb[i] = bb[i] + i;
}
{
int s = 112728283;
int ar[8];
for (i = 0; i < 8; i++)
ar[i] = s * 17 * i;
}
cc = (int*)_alloca(x);
if (((int)cc) & 0x3)
fail = 1;
cc[0] = 0;
cc[1] = 1;
cc[2] = 2;
cc[3] = 3; // <--- Boom!
for (i = 0; i < x; i++)
if (bb[i] != (7 + i))
fail = 1;
if (tmp != k)
fail = 1;
if (fail) {
printf("fail\n");
exit(7);
}
printf("%d\n", (*cc) / y);
printf("fail\n");
exit(7);
}
__except (1)
{
for (i = 0; i < SIZE; i++)
if (aa[i] != (x + i + 1))
fail = 1;
if (fail) {
printf("fail\n");
exit(7);
}
printf("pass\n");
exit(0);
}
}
若要建置及測試此範例,請在Visual Studio 2019 16.9版或更新版本的 開發人員命令提示字元中執行下列命令:
cl example3.cpp /fsanitize=address /Zi
devenv /debugexe example3.exe
產生的錯誤 - 對 alloca 的數次呼叫
另請參閱
AddressSanitizer 概觀
AddressSanitizer 已知問題
AddressSanitizer 組建和語言參考
AddressSanitizer 運行時間參考
AddressSanitizer 陰影位元組
AddressSanitizer 雲端或分散式測試
AddressSanitizer 調試程式整合
AddressSanitizer 錯誤範例