Error: heap-use-after-free
Address Sanitizer Error: Use of deallocated memory
We show three examples where storage in the heap can be allocated via malloc, realloc (C), and new (C++), along with a mistaken use of volatile.
Example - malloc
// example1.cpp
// heap-use-after-free error
#include <stdlib.h>
int main() {
char *x = (char*)malloc(10 * sizeof(char));
free(x);
// ...
return x[5]; // Boom!
}
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
Example - operator new
// example2.cpp
// heap-use-after-free error
#include <windows.h>
int main() {
char *buffer = new char[42];
delete [] buffer;
// ...
buffer[0] = 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 example2.cpp /fsanitize=address /Zi
devenv /debugexe example2.exe
Resulting error - operator new
Example - realloc
// example3.cpp
// heap-use-after-free error
#include <malloc.h>
int main() {
char *buffer = (char*)realloc(0, 42);
free(buffer);
// ...
buffer[0] = 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 example3.cpp /fsanitize=address /Zi
devenv /debugexe example3.exe
Resulting error - realloc
Example - volatile
// example4.cpp
// heap-use-after-free error
#include <stdlib.h>
int main() {
volatile char *x = (char*)malloc(sizeof(char));
free((void*)x);
//...
*x = 42; // Boom!
}
To build and test this example, run these commands in a Visual Studio 2019 version 16.9 or later developer command prompt:
cl example4.cpp /fsanitize=address /Zi
devenv /debugexe example4.exe
Resulting error - volatile
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
Maklum balas
Kirim dan lihat maklum balas untuk