Trying to suppress clang false positive leak warning
Asked Answered
M

1

9

I am using clang static analysis under Xcode 6.4 (6E35b), and getting a false positive warning about a potential memory leak. I do explicitly free the memory in question, but the freeing happens in a different compilation unit. Here is my MWE:

file2.c: Performs the actual freeing.

#include <stdlib.h>
void my_free(const void* p) {
    free((void*) p);
}

file1.c: Allocates memory and explicitly frees it through an external function.

#include <stdlib.h>
void my_free(const void* p);

int main(int argc, char* argv[]) {
    void* data = malloc(1);
    if(data) my_free(data);
    return 0; /* <-- "Potential leak of memory pointed to by 'data'" */
}

When I define my_free() in the same compilation unit as its invocation, no warning is generated, but of course I need to invoke my_free() from a large number of different source files.

I have read through FAQ and How to Deal with Common False Positives, but it does not address my situation. What can I do to assure clang that I really am freeing the memory in question?

In case the version information is relevant:

% clang --version
Apple LLVM version 6.1.0 (clang-602.0.53) (based on LLVM 3.6.0svn)
Mccabe answered 12/5, 2017 at 14:57 Comment(2)
On a side note, I would expect "my_free" to come in pair with "my_malloc".Dimond
@Groo: Good point. This MWE may be a little misleading in what it suggests, but I agree that allocation and deallocation should generally come in pairs.Mccabe
O
7

One way to fix that would be to add code specific for the analyser, in your header file:

#ifdef __clang_analyzer__
#define my_free free
#endif

This will make the static analyser think you're using the classic free function and stop complaining.

Oneida answered 12/5, 2017 at 15:15 Comment(2)
Good to know +1Newsy
A wonderful solution. In context I have to do things a little differently or the compiler complains when I try to define function my_free(), but the principle holds. Thank you.Mccabe

© 2022 - 2024 — McMap. All rights reserved.