Error: double-free
Address Sanitizer Error: Deallocation of freed memory
In C, you can call free
erroneously. In C++, you can call delete
more than once. In these examples, we show errors with delete
, free
, and HeapCreate
.
// example1.cpp
// double-free error
int main() {
int *x = new int[42];
delete [] x;
// ... some complex body of code
delete [] x;
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
devenv /debugexe example1.exe
// example2.cpp
// double-free 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];
free(x);
// ... some complex body of code
free(x + argc - 1); // Boom!
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 example2.cpp /fsanitize=address /Zi
devenv /debugexe example2.exe
// example3.cpp
// double-free error
#include <Windows.h>
#include <stdio.h>
int main() {
void* newHeap = HeapCreate(0, 0, 0);
void* newAlloc = HeapAlloc(newHeap, 0, 100);
HeapFree(newHeap, 0, newAlloc);
HeapFree(newHeap, 0, newAlloc);
printf("failure\n");
return 1;
}
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
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