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)
Josh Sanford
  • 622
  • 5
  • 18
  • On a side note, I would expect "`my_free`" to come in pair with "`my_malloc`". – vgru May 12 '17 at 15:19
  • @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. – Josh Sanford May 12 '17 at 15:45

1 Answers1

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.

blue112
  • 52,634
  • 3
  • 45
  • 54