Note 22.6.1.
AddressSanitizer does not work on GCC for Windows. But it does work when using GCC on Windows Subsystem for Linux (WSL).
-fsanitize=address
flag. It is most useful if you also use the -g
flag to include debug information in the compiled binary.
$ g++ -fsanitize=address -g detect-leaks.cpp -o program.exe
new int(5)
and another for the string allocated with new string("Hello, world")
. Add the line delete p1;
at the end of foo, and run the program again. Now you should only get one memory leak (the one for the string).
Direct leak of 32 byte(s) in 1 object(s) allocated from: #0 0x7f058b6bb548 in operator new(unsigned long) ../../../../src/libsanitizer/asan/asan_new_delete.cpp:95 #1 0x55792de515bd in foo() /home/jobe/runs/jobe_9E1yY2/test.cpp:10 #2 0x55792de51805 in main /home/jobe/runs/jobe_9E1yY2/test.cpp:19 #3 0x7f058b0401c9 (/lib/x86_64-linux-gnu/libc.so.6+0x2a1c9) (BuildId: 42c84c92e6f98126b3e2230ebfdead22c235b667) #4 0x7f058b04028a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2a28a) (BuildId: 42c84c92e6f98126b3e2230ebfdead22c235b667) #5 0x55792de51404 in _start (/home/jobe/runs/jobe_9E1yY2/test.cpp.exe+0x2404) (BuildId: 2d2506729042a70f415e3a189abe98bf4c37c123)
"Direct leak of 32 byte(s) in 1 object(s) allocated from:"
).#n ADDRESS in FUNCTION (FILE:LINE)
.
ADDRESS
is the memory address where the allocation occurred.FUNCTION
, FILE
, and LINE
number indicate where in the code the allocation was made.new
from the asan library. We probably donβt care about that. The library did not cause our leak.
new
was called from foo()
on line 10 of test.cpp
. (Donβt worry about /home/jobe/runs/jobe_5QqFtF/
, that is just the folder on the server the code was in when it ran.) This is the important piece of information. It is the first code that we wrote that is responsible for the leak.
foo()
was called from main
on line 19 of test.cpp
. This is also important because it shows us the chain of function calls that led to the leak. If foo()
was called multiple times, this would help us figure out which call was responsible for the leak.
foo()
by making it look like:
...
cout << "p2 points to: " << *p2 << endl;
delete p1;
cout << *p1; // Use after free error
}
...
==55472==ERROR: AddressSanitizer: heap-use-after-free on address 0x502000000010 at pc 0x55817502f795 bp 0x7ffd453d5840 sp 0x7ffd453d5830 READ of size 4 at 0x502000000010 thread T0 #0 0x55817502f794 in foo() /home/jobe/runs/jobe_nZISUA/test.cpp:16 ...
0x502000000010
after freeing it. We used it on line 16 of test.cpp
. Looking down further, we can see a report about when it was freed:
... 0x502000000010 is located 0 bytes inside of 4-byte region [0x502000000010,0x502000000014) freed by thread T0 here: #0 0x7ff94b2635e8 in operator delete(void*, unsigned long) ../../../../src/libsanitizer/asan/asan_new_delete.cpp:164 #1 0x55817502f75a in foo() /home/jobe/runs/jobe_nZISUA/test.cpp:15 ...