Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find memory leaks with Clang

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.

like image 564
Sai Ram Avatar asked Jul 02 '15 07:07

Sai Ram


People also ask

How do you detect a memory leak?

The best approach to checking for the existence of a memory leak in your application is by looking at your RAM usage and investigating the total amount of memory been used versus the total amount available. Evidently, it is advisable to obtain snapshots of your memory's heap dump while in a production environment.

How do you fix a Leaksanitizer detected memory leak?

To fix it just move the malloc so it's after the loop. void Insert(int x){ struct Node* ptr = head; //check if already present while(ptr != NULL){ if(ptr->data == x){return;} ptr = ptr->next; } struct Node* temp = malloc(sizeof(struct Node));

Is Valgrind a sanitizer?

Valgrind uses dynamic instrumentation instead of static instrumentation at compile time, which leads to the high performance overhead that can be impractical for CPU-intensive applications. Sanitizers uses static instrumentation and allows for similar checks with a lower overhead.

What is Fsanitize?

The /fsanitize=address compiler option enables AddressSanitizer, a powerful compiler and runtime technology to uncover hard-to-find bugs. Support for the /fsanitize=address option is available starting in Visual Studio 2019 version 16.9.


1 Answers

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;
  ^~~~~~~~
like image 70
Max Smolens Avatar answered Sep 19 '22 19:09

Max Smolens