Search code examples
cgccaddress-sanitizer

Does not AddressSanitizer trace memory leak from global variable?


I'm trying to use -fsanitize=address with gcc.

I declare global variable(ex. int*) and allocate memory with malloc, then I didn't call free function. I expect the sanitizer will show up error message about memory leak, but it exit with no error message. So, I use local variable for test. Sanitizer works well on that test code. I put my codes below.

this is a global variable code.

#include<stdio.h>
#include<stdlib.h>
int *gv;

int main(){
    gv = (int*)malloc(sizeof(int)*4);
    printf("yooooolooooooo\n");
    return 0;
}

and this is local variable code.

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

int main(){
    int *gv = (int*)malloc(sizeof(int)*4);
    printf("yooooolooooooo\n");
    return 0;
}

I compile with gcc -fsanitize=address -o test test.c.

upper code shows me just

yooooolooooooo

but local variable code shows

yooooolooooooo

=================================================================
==15484==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 16 byte(s) in 1 object(s) allocated from:
    #0 0x7f6e43395b60 in __interceptor_malloc (/usr/lib/x86_64-linux-gnu/libasan.so.5+0xedb60)
    #1 0x564b5f8bd936 in main (/home/jiho/lab/test+0x936)
    #2 0x7f6e42ed8b96 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21b96)

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

I wonder why sanitizer doesn't works with global variable...

thank you and i hope someone knows about it.

ps. my system is ubuntu 18.04 and x86_64.


Solution

  • Similar to Valgrind LeakSanitizer reports only "direct" leaks i.e. addresses that are no longer accessible from any existing user data (called "root-set" in LSan design document). In case of global variable the address is obviously still accessible.