5

I'm trying to learn how to use -fsanitize=address -fno-omit-frame-pointer to detect memory leaks. I wrote something simple which clearly has a memory leak in it, but compiling with gcc -fsanitize=address -fno-omit-frame-pointer file.c and then executing the function doesn't seem to have a problem.

This post seems to indicate that we need to set botth the compiler flag and linker flag and NOT to use -lasan How to use AddressSanitizer in gcc?.

I don't think it is necessary, but I've tried gcc -fsanitize=address -static-libasan -fno-omit-frame-pointer s.c as the docs seem mention here. https://gcc.gnu.org/onlinedocs/gcc/Link-Options.html

I also tried following this: https://lemire.me/blog/2016/04/20/no-more-leaks-with-sanitize-flags-in-gcc-and-clang/

Just in case this is relevant, I'm on MacOS. I've updated and upgraded gcc via brew. The version info is: Apple LLVM version 10.0.1 (clang-1001.0.46.4)

Here's the dummy code that I wrote:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv) {
    char *buffer = malloc(1024);
    sprintf(buffer, "%d", argc);
    printf("%s\n", buffer);
    buffer = malloc(10);
    buffer[0] = 'A';
    buffer[9] = '\0';
    printf("%s\n", buffer);
}

I never freed anything so I expect the address sanitizer to catch it. But when I run the code I get the following:

$ ./s
1
A????????

What am I misunderstanding/doing wrong?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
dlin168
  • 61
  • 1
  • 1
  • 3
  • 1
    You're using clang, not gcc (Apple has gcc set up as an alias for clang in Xcode for some reason and all it does is confuse people). But both compilers are the same; compile and link with `-g -fsanitize=address`. – Shawn Oct 07 '19 at 03:03
  • Also, comments dated earlier this year in the lemire link in your question say that the Apple version of asan doesn't do leak detection. – Shawn Oct 07 '19 at 03:08
  • AFAIK -fsanitize=address isn't supposed to catch memory leaks, that's what -fsanitize=leak is for. The address sanitizer should catch out-of-bounds array access (try writing to buffer[10] in your code) as well as use-after-free bugs, but neither of those bugs is present in your code. EDIT: i'd also suggest using -lasan, even though the post you linked suggests otherwise. I always use -lasan and it works for me (Linux + GCC) – Felix G Oct 07 '19 at 08:20
  • Did you set `ASAN_OPTIONS=detect_leaks=1` as explained at https://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer? – Marc Glisse Oct 07 '19 at 12:52
  • I see. I didn't realize I was using clang, not gcc. So b/c Apple's version of asan doesn't do leak detection that's why I'm not getting errors. Also it seems like I should be using `fsanitize=leak`. I'll try it out witth `-lasan` as well. No I didn't know about the options and I haven't come across that link. Thanks! – dlin168 Oct 09 '19 at 15:07

0 Answers0