gcc gives me maybe-uninitialized warning when passing void * to a function accepting const void *

Viewed 42

This code:

class X {
};

void f(const void *) {
}

int main() {
    X a;
    void *p = &a;
    f(p);
}

compiled with g++ -Wall test.cpp issues warning

test.cpp: In function ‘int main()’:
test.cpp:10:6: warning: ‘p’ may be used uninitialized [-Wmaybe-uninitialized]
   10 |     f(p);
      |     ~^~~
test.cpp:4:6: note: by argument 1 of type ‘const void*’ to ‘void f(const void*)’ declared here
    4 | void f(const void *) {
      |      ^
test.cpp:8:7: note: ‘a’ declared here
    8 |     X a;
      |       ^

However when optimizations are enabled (with -O1, -O2, or -O3) the warning disappears.

Is this a compiler bug?

0 Answers
Related