Catalin Demergian
Catalin Demergian

Reputation: 97

Is Address Sanitizer suppose to work with optimizations enabled?

I want to use Address Sanitizer to find violations

int main()
{
    int v[] = {1, 2, 3};
    int val = v[3];

    printf("exiting main\n");
    return 0;
}
    

g++ -W -Wall -fsanitize=address -o my_bin main.cpp -> I get a lot of output from the sanitizer

g++ -O2 -W -Wall -fsanitize=address -o my_bin main.cpp -> just "exiting main"

So, the adding of -O2 flag makes Address Sanitizer not finding violations. Is this right?

I tried in a Ubuntu VM, architecture is x86.

g++ --version
g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Upvotes: 3

Views: 1143

Answers (1)

ks1322
ks1322

Reputation: 35736

So, the adding of -O2 flag makes Address Sanitizer not finding violations

Not exactly. Adding -O2 flag can make gcc to optimize out unused variable val and Address Sanitizer does not see array subscript out of bounds error at runtime. If you do use val variable in your code, both optimized and not optimized build will output Address Sanitizer error.

int main()
{
    int v[] = {1, 2, 3};
    int val = v[3];

    printf("exiting main\n");
    return val;
}

This code will always output stack-buffer-overflow error.

Upvotes: 4

Related Questions