9

I have installed Clang in my machine (ubuntu) in order to find memory leaks in my C code. I wrote a sample code in order to check the working of it which is as follows:

/* 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 in internet to compile like

$ scan-build clang --analyze hello.c

and

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

But none of them are showing any signs of memory leak.

scan-build: Using '/usr/bin/clang' for static analysis
scan-build: Removing directory '/tmp/scan-build-2015-07-02-122717-16928-1' because it contains no reports.
scan-build: No bugs found.

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

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Sai Ram
  • 101
  • 1
  • 3
  • Use [valgrind](http://valgrind.org) when testing your program. Such bugs are impossible to find statically in the general case (but some tools might find some bugs heuristically or conservatively). And `-fsanitize=address` adds *runtime checks* so you need to run the program. – Basile Starynkevitch Jul 02 '15 at 07:03
  • did you try `$ scan-build clang -fsanitize=address -g hello.c`? – Sourav Ghosh Jul 02 '15 at 07:04
  • $ scan-build clang -fsanitize=address -g hello.c yes i tried – Sai Ram Jul 02 '15 at 07:06
  • Look at the generated code to verify that the compiler didn't optimise away the body of `main`. – molbdnilo Jul 02 '15 at 08:10

1 Answers1

4

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

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

Analyzing this code by running:

scan-build clang -g hello.c

gives a warning like:

hello.c:9:3: warning: Potential leak of memory pointed to by 'x'
  return 0;
  ^~~~~~~~
Max Smolens
  • 3,461
  • 26
  • 34
  • also, if you use use clang++ and say `x = nullptr` instead of 'x = 0`, even with the global variable, it detects it. – matiu Sep 09 '18 at 23:57