Skip to content

Latest commit

 

History

History
90 lines (64 loc) · 2.84 KB

error-stack-buffer-underflow.md

File metadata and controls

90 lines (64 loc) · 2.84 KB
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
stack-buffer-underflow
stack-buffer-underflow error
AddressSanitizer error stack-buffer-underflow

Error: stack-buffer-underflow

Address Sanitizer Error: Stack buffer underflow

These error messages indicate a memory access to somewhere before the beginning of a stack variable.

Example - local array underflow

// 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.

Resulting error

:::image type="content" source="media/stack-buffer-underflow-example-1.png" alt-text="Screenshot of debugger displaying stack-buffer-underflow error in example 1.":::

Example - stack underflow on thread

// 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

Resulting error - stack underflow on thread

:::image type="content" source="media/stack-buffer-underflow-example-2.png" alt-text="Screenshot of debugger displaying stack-buffer-underflow error in example 2.":::

See also

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