I have issue while running clang on an android service on some cpp file. I am creating an intentional memory leak by calling an object instance from another class without deleting it to see if clang creates memory leak warning or not but for some cases It is not creating memory leak warning.
1- If I put a class declaration in same header file with the class that I wanted to create a memory leak, clang catching the memory leak as the following:
Example.h
class Ad
{
public:
void xx();
};
class Example
{
public:
bool getData();
};
Example.cpp
#include "Example.h"
void Ad::xx()
{
bool ar = false;
ar = true;
}
bool Example::getData()
{
char *ptrt;
ptrt = (char*)malloc(10*sizeof(char));
snprintf(ptrt,10,"%s","trial");
Ad *arr = new Ad();
arr->xx();
return true;
}
In this example, clang can catch 2 memory leaks in getData() function.
2-If I create class Ad declaration in separate header file than clang can not catch memory leak:
Ad.h
class Ad
{
public:
void xx();
};
Ad.cpp
#include "Ad.h"
void Ad::xx()
{
bool ar = false;
ar = true;
}
Example.h
class Example
{
public:
bool getData();
};
Example.cpp
#include "Example.h"
#include "Ad.h"
bool Example::getData()
{
Ad *arr = new Ad();
arr->xx();
//Clang can not catch memory leak error here..
return true;
}
Notes:
I am exporting WITH_STATIC_ANALYZER=1 on aosp android/ folder
and running mmma module_name/ .
I am using Android P for aosp.
I also initialized this flags in Android.bp
cflags:[
"-Wall",
"-Werror",
"-Wunused",
"-Wunreachable-code",
],
Is there any idea why that may happen ?
I'm not so familiar with clang's analyzer; however I think 2 things happen in the second case compared to the first:
1) When compiling, you're calling clang twice, creating 2 object files, each with one of the functions. Hence analyzer data cannot pass through from
Ad::xx
toExample::getData
.2) From the point of view of the Example.cpp clang invocation, nothing guarantees that
Ad::xx
does not store a reference to theAd
object on which it is called, thus its lifetime could be longer than theExample::getData
scope. Hence no memory leak warning.Try using the same input file for both implementations; that should make it work.