3

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)

jhasse
  • 2,379
  • 1
  • 30
  • 40
  • The answer is in following link: https://stackoverflow.com/a/33995232/994042. "As long as you do not call release_*, protobuf will take care of deleting the object. If you need the Object after dealing with the Protobuf Message, you need to relase it using release_*, which will prevent Protobuf to delete your object." – Thien Tran Feb 15 '21 at 07:47
  • That just tells me that the warning is a false-positive. How do I avoid it? – jhasse Feb 15 '21 at 11:46
  • You can disable check with: clang-tidy test.cpp -checks=-clang-analyzer-cplusplus.NewDeleteLeaks – Thien Tran Feb 16 '21 at 14:17
  • 2
    That's even worse than using `// NOLINT`, because it will also disable other useful messages. So this is just a bug in clang-tidy? – jhasse Feb 17 '21 at 13:55
  • "POTENTIAL memory leak" mean in this place the memory MAY not be freed. You can manual free it by yourself. It's not a bug of clang-tidy, it may be a bug of a check of clang-tidy. – Thien Tran Feb 17 '21 at 20:30
  • The memory will always be freed by the protobuf object and will never leak. – jhasse Feb 17 '21 at 20:39

1 Answers1

1

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.

kkpattern
  • 948
  • 2
  • 7
  • 31