Why is address sanitizer not detecting this simple memory leak?

Viewed 944

Does anybody have any idea why address sanitizer is not flagging this very obvious memory leak

class A {
public:
    A() = default;
};

TEST_F(LibrdfSerializerTests, Test) {
    A* a = new A;
}

built with the following added to cmake:

    set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -fno-omit-frame-pointer -fsanitize=address")
    set(CMAKE_LINKER_FLAGS_DEBUG "${CMAKE_LINKER_FLAGS_DEBUG} -fno-omit-frame-pointer -fsanitize=address")

1 Answers

You can try using the ASAN_OPTIONS=detect_leaks=1 while executing the binary to detect leaks. Using the example from the documentation

❯ cat leak.c
#include <stdlib.h>
void *p;
int main() {
  p = malloc(7);
  p = 0; // The memory is leaked here.
  return 0;
}

Compile the program

clang -fsanitize=address -g leak.c

and then execute it as follows:

ASAN_OPTIONS=detect_leaks=1 ./a.out

Output:

=================================================================
==63987==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 7 byte(s) in 1 object(s) allocated from:
    #0 0x1034c109d in wrap_malloc+0x9d (libclang_rt.asan_osx_dynamic.dylib:x86_64h+0x4609d)
    #1 0x103477ef8 in main leak.c:4
    #2 0x7fff6b30fcc8 in start+0x0 (libdyld.dylib:x86_64+0x1acc8)

SUMMARY: AddressSanitizer: 7 byte(s) leaked in 1 allocation(s).

Same for CPP

❯ cat memory-leak.cpp
#include <cstdlib>
#include <cstdio>
class A {
public:
    A() = default;
};

int main() {
    char const* asanOpt = std::getenv("ASAN_OPTIONS");
    std::printf("%s\n", asanOpt);
    A* a = new A;
    return 0;
}

Compile it

clang++ -g memory-leak.cpp -fsanitize=address

While executing the binary, use the option to enable leak detections

ASAN_OPTIONS=detect_leaks=1 ./a.out

Output:

detect_leaks=1

=================================================================
==69309==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 1 byte(s) in 1 object(s) allocated from:
    #0 0x109ea556d in wrap__Znwm+0x7d (libclang_rt.asan_osx_dynamic.dylib:x86_64h+0x5256d)
    #1 0x109e4bf48 in main memory-leak.cpp:7
    #2 0x7fff6b30fcc8 in start+0x0 (libdyld.dylib:x86_64+0x1acc8)

SUMMARY: AddressSanitizer: 1 byte(s) leaked in 1 allocation(s).

Tested on:

MacOS 10.15

With clang

clang version 10.0.1 
Target: x86_64-apple-darwin19.6.0
Thread model: posix
Related