1.Background
- Let's consider a C file
a.cwith following content as a memory leak MRE:
#include <stdlib.h>
void Foo() { malloc(1); }
int main() { Foo(); return 0;}
- On one hand, as expected, Clang LeakSanitizer (which is integrated into Clang AddresSanitizer) detects the memory leak if the following command is run:
$ clang++ -g -fsanitize=address a.c; ./a.out
=================================================================
==...==ERROR: LeakSanitizer: detected memory leaks
Direct leak of 1 byte(s) in 1 object(s) allocated from:
#0 0x... in malloc (/.../a.out+0xa114e) (BuildId: ...)
#1 0x... in Baz() (/.../a.c:2:14
#2 0x... in main (/.../a.c:3:14
#3 0x... in __libc_start_call_main csu/../sysdeps/nptl/libc_start_call_main.h:58:16
SUMMARY: AddressSanitizer: 1 byte(s) leaked in 1 allocation(s).
- On the other hand, Clang AddressSanitizer documentation Usage section mentions:
To get a reasonable performance add
-O1or higher.
2.Concern
- Clang LeakSanitizer does not detect the memory leak if the following command is run (the code generation option
-O1has been added):
$ clang++ -O1 -g -fsanitize=address a.c; ./a.out
3.Question
Can memory leak still be detected by Clang LeakSanitizer when code optimization level 1 or higher is used?
If the answer is yes, please provide a minimal reproducible example (MRE) proving it.
If the answer is no, please explain why (link to Clang compiler source code, ...).
4.Remarks
Clang LeakSanitizer documentation Usage section does not explicitly mention that code optimization shall not be used.
Above observations were made with version 18 of Clang, installed on Linux Ubuntu 22.04.3 using LLVM automatic installation script.
As explained by user17732522 in a comment, the
a.cfile example in the Background section does not lead to memory leak detection when the-O1option is used because:
The optimized program won't have any actual memory leak. The malloc call will be optimized away since it doesn't affect observable behavior
Your minimal example is too minimal --
clangwas able to optimize everything away from it:As you can see, none of
Fooormallocremain.To make it a bit more realistic, try this:
And now with
-O1: