Memory errors like use-after-free, buffer overflows, and memory leaks are some of the most common bugs in C and C++ - and some of the hardest to debug. Fortunately, the AddressSanitizer tool, available via gcc or g++ compiler, makes it easy to catch these issues at runtime. This tutorial demonstrates how to detect memory errors with AddressSanitizer using gcc or g++ compiler.
Let's say we have the following code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char *buff = malloc(20);
strcpy(buff, "Hello world");
free(buff);
printf("%s\n", buff);
return 0;
}
This code allocates memory, copies a string, frees the memory, and then accesses the freed memory - a classic use-after-free error.
To enable AddressSanitizer, compile the code with the -fsanitize=address
option. Example:
gcc -g -fsanitize=address main.c -o test
The -g
option is optional but recommended for better symbol output in error messages.
Example output (truncated):
==6614==ERROR: AddressSanitizer: heap-use-after-free on address 0x503000000040 at pc 0x712b0da6cf85 bp 0x7fff706cefe0 sp 0x7fff706ce788
READ of size 2 at 0x503000000040 thread T0
#0 0x712b0da6cf84 in puts ../../../../src/libsanitizer/sanitizer_common/sanitizer_common_interceptors.inc:1236
#1 0x6485063e6275 in main /home/testuser/myproject/main.c:9
#2 0x712b0d62a1c9 in __libc_start_call_main ../sysdeps/nptl/libc_start_call_main.h:58
#3 0x712b0d62a28a in __libc_start_main_impl ../csu/libc-start.c:360
#4 0x6485063e6164 in _start (/home/testuser/myproject/test+0x1164) (BuildId: 790df7b5a0553d15a4cb87bbcbbb5b94287fc73a)
0x503000000040 is located 0 bytes inside of 20-byte region [0x503000000040,0x503000000054)
...
AddressSanitizer detected a heap-use-after-free error on line 9 of the main.c
file.
In the same way, AddressSanitizer can also be used with g++ for C++ code
Leave a Comment
Cancel reply