Clang Static Analyzer complains about memory leak when using protobuf's set_allocated_*

Viewed 491

With the following proto file

message Foo {
    // ...
}

message MyMessage {
    Foo foo = 1;
}

I set foo with the generated set_allocated_foo method which takes ownership of the pointer:

MyMessage m;
m.set_allocated_foo(new Foo);

clang-tidy gives me the following warning though when m leaves the scope:

warning: Potential memory leak [clang-analyzer-cplusplus.NewDeleteLeaks]
}
^
note: Memory is allocated
    m.set_allocated_foo(new Foo);
                        ^

Is there any way to avoid that? (without using // NOLINT)

1 Answers

One way you can do is using #ifdef __clang_analyzer__:

MyMessage m;
auto* f = new Foo;
m.set_allocated_foo(f);
#ifdef __clang_analyzer__
delete f
#endif

I don't know if it's the best way.

Related