How to find memory leaks using Clang

I installed Clang on my computer (ubuntu) to find memory leaks in my C code. I wrote a sample code to test its operation, which looks like this:

/* File: hello.c for leak detection */ #include <stdio.h> #include <stdlib.h> void *x; int main() { x = malloc(2); x = 0; // Memory leak return 0; } 

I found some options on the Internet to compile as

 $ scan-build clang --analyze hello.c 

and

 $ scan-build clang -fsanitize=address hello.c 

But none of them show any signs of a memory leak.

scan-build: Using / usr / bin / clang for static analysis
scan-build: Delete the directory '/ tmp / scan-build-2015-07-02-122717-16928-1' because it does not contain reports.
scan-build: no errors were found.

Can anyone tell how to properly use Clang leak detection for Memory.

+6
source share
1 answer

Interestingly, the clang static analyzer detects a memory leak if you declare void *x inside main :

 int main() { void *x = malloc(2); x = 0; // Memory leak return 0; } 

Parsing this code with:

 scan-build clang -g hello.c 

gives a warning, for example:

 hello.c:9:3: warning: Potential leak of memory pointed to by 'x' return 0; ^~~~~~~~ 
+2
source

All Articles