Edit

Share via


Error: heap-buffer-overflow

Address Sanitizer Error: Heap buffer overflow

This example demonstrates the error that results when a memory access occurs outside the bounds of a heap-allocated object.

Example - classic heap buffer overflow

// example1.cpp
// heap-buffer-overflow error
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv) {

    char *x = (char*)malloc(10 * sizeof(char));
    memset(x, 0, 10);
    int res = x[argc * 10];  // Boom!

    free(x);
    return res;
}

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
devenv /debugexe example1.exe

Resulting error

Screenshot of debugger displaying heap-buffer-overflow error in example 1.

Example - improper down cast

// example2.cpp
// heap-buffer-overflow error
class Parent {
public:
    int field;
};

class Child : public Parent {
public:
    int extra_field;
};

int main(void) {
    Parent *p = new Parent;
    Child *c = (Child*)p;  // Intentional error here!
    c->extra_field = 42;

    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 - improper down cast

Screenshot of debugger displaying heap-buffer-overflow error in example 2.

Example - strncpy into heap

// example3.cpp
// heap-buffer-overflow error
#include <string.h>
#include <stdlib.h>

int main(int argc, char **argv) {

    char *hello = (char*)malloc(6);
    strcpy(hello, "hello");

    char *short_buffer = (char*)malloc(9);
    strncpy(short_buffer, hello, 10);  // Boom!

    return short_buffer[8];
}

To build and test this example, run these commands in a Visual Studio 2019 version 16.9 or later developer command prompt:

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

Resulting error - strncpy into heap

Screenshot of debugger displaying heap-buffer-overflow error in example 3.

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