| title | Error: heap-buffer-overflow | ||
|---|---|---|---|
| description | Source examples and live debug screenshots for heap variable overflow errors. | ||
| ms.date | 03/02/2021 | ||
| f1_keywords |
|
||
| helpviewer_keywords |
|
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.
// 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:::image type="content" source="media/heap-buffer-overflow-example-1.png" alt-text="Screenshot of debugger displaying heap-buffer-overflow error in example 1.":::
// 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:::image type="content" source="media/heap-buffer-overflow-example-2.png" alt-text="Screenshot of debugger displaying heap-buffer-overflow error in example 2.":::
// 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:::image type="content" source="media/heap-buffer-overflow-example-3.png" alt-text="Screenshot of debugger displaying heap-buffer-overflow error in example 3.":::
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