Search code examples
c++debuggingmemory-leaksaddress-sanitizermemory-leak-detector

LeakSanitizer and leaky libraries


I am trying to use gcc's leak sanitizer option to detect leaks in my program.

For this I compile with the relevant flags, run my program, then terminate, which results in the following output:

==8013==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 72704 byte(s) in 1 object(s) allocated from:
    #0 0x7f3ace944ada in __interceptor_malloc /build/gcc/src/gcc/libsanitizer/asan/asan_malloc_linux.cc:144
    #1 0x7f3ab2f8690d  (<unknown module>)
    #2 0x7f3ab2f50525  (<unknown module>)

Direct leak of 72704 byte(s) in 1 object(s) allocated from:
    #0 0x7f3ace944ada in __interceptor_malloc /build/gcc/src/gcc/libsanitizer/asan/asan_malloc_linux.cc:144
    #1 0x7f3ab51d2aad  (<unknown module>)
    #2 0x7f3ab51c4475  (<unknown module>)

Direct leak of 256 byte(s) in 1 object(s) allocated from:
    #0 0x7f3ace944ada in __interceptor_malloc /build/gcc/src/gcc/libsanitizer/asan/asan_malloc_linux.cc:144
    #1 0x562db822861c in RenderHandler::RenderHandler() ../Src/main.cpp:68
    #2 0x562db8226ee2 in main ../Src/main.cpp:200
    #3 0x7f3acdf61ee2 in __libc_start_main (/usr/lib/libc.so.6+0x26ee2)

Direct leak of 232 byte(s) in 5 object(s) allocated from:
    #0 0x7f3ace944ada in __interceptor_malloc /build/gcc/src/gcc/libsanitizer/asan/asan_malloc_linux.cc:144
    #1 0x7f3ab3e31677  (<unknown module>)
[...]

From what I have been told, many libraries (even the standard libraries) can have leaky code, which I am not terribly worried about. If my video driver has leaky code, I am not going to fix that.

However in the above stack trace there is one relevant leak (third one reported). That one I added on purpose.

I want to not print any leaks that happen in "unknown modules" since I can't fix a leak that occurs in a place I don't know (these are likely coming from third party libraries), and they have a tendency to hide the leaks I can actually fix.

Is there a mechanism to instruct leak sanitizer to avoid printing certain kinds of leaks?


Solution

  • Use a suppressions file, as documented on AddressSanitizerLeakSanitizer#suppressions:

    You can instruct LeakSanitizer to ignore certain leaks by passing in a suppressions file. The file must contain one suppression rule per line, each rule being of the form leak:<pattern>. The pattern will be substring-matched against the symbolized stack trace of the leak. If either function name, source file name or binary file name matches, the leak report will be suppressed.

    You pass the file at runtime by setting the environment variable LSAN_OPTIONS=suppressions:my_suppressions.txt.

    In your particular case, it may be difficult to find a good string to match against due to the <unknown module> entries. Passing -fno-omit-frame-pointer to the compiler might help to get better stack traces (which are helpful during debugging anyway).