title | description | ms.date | f1_keywords | helpviewer_keywords | |||
---|---|---|---|---|---|---|---|
Error: stack-buffer-underflow |
Source examples and live debug screenshots for Stack buffer underflow errors. |
03/02/2021 |
|
|
Address Sanitizer Error: Stack buffer underflow
These error messages indicate a memory access to somewhere before the beginning of a stack variable.
// example1.cpp
// stack-buffer-underflow error
#include <stdio.h>
int main() {
int subscript = -1;
char buffer[42];
buffer[subscript] = 42; // Boom!
return 0;
}
To build and test this example, run these commands in a Visual Studio 2019 version 16.9 or later developer command prompt:
cl example1.cpp /fsanitize=address /Zi /Od
devenv /debugexe example1.exe
ASAN is a form of dynamic analysis, which means it can only detect bad code that is actually executed. An optimizer will remove the assignment to buffer[subscript]
because buffer[subscript]
is never read from. As a result, this example requires the /Od
flag.
:::image type="content" source="media/stack-buffer-underflow-example-1.png" alt-text="Screenshot of debugger displaying stack-buffer-underflow error in example 1.":::
// example2.cpp
// stack-buffer-underflow error
#include <windows.h>
DWORD WINAPI thread_proc(void *) {
int subscript = -1;
volatile char stack_buffer[42];
stack_buffer[subscript] = 42;
return 0;
}
int main() {
HANDLE thr = CreateThread(NULL, 0, thread_proc, NULL, 0, NULL);
if (thr == 0) return 0;
WaitForSingleObject(thr, INFINITE);
return 0;
}
To build and test this example, run these commands in a Visual Studio 2019 version 16.9 or later developer command prompt:
cl example2.cpp /fsanitize=address /Zi
devenv /debugexe example2.exe
:::image type="content" source="media/stack-buffer-underflow-example-2.png" alt-text="Screenshot of debugger displaying stack-buffer-underflow error in example 2.":::
AddressSanitizer overview
AddressSanitizer known issues
AddressSanitizer build and language reference
AddressSanitizer runtime reference
AddressSanitizer shadow bytes
AddressSanitizer cloud or distributed testing
AddressSanitizer debugger integration
AddressSanitizer error examples