Please let me know if I can do it or not?
I am writing a library that could work to track memory allocation and de-allocation in C++. In short, I am trying to see if
Finally I got an answer by one of similar threads in this forum... The following code worked... Lets say,
class A
{
public:
char str[1000];
A()
{
strcpy(str,"Default string");
}
A(const char* s)
{
strcpy(str,s);
}
};
void * operator new (unsigned size, char const * file, int line)
{
cout << "File = " << file << endl;
cout << "Line = " << line << endl;
return( malloc(size));
}
#define new new(__FILE__, __LINE__)
int main()
{
A *a = new A("Leak");
printf("%s",a->str);
delete a;
return 0;
}
Related post where I found the answer... overloading new and delete in c++
You can use the studio dbx run time checking feature to identify memory leaks under Solaris ( http://blogs.oracle.com/janitor/entry/runtime_memory_checking .) libumem can also be very helpful ( http://blogs.oracle.com/pnayak/entry/finding_memory_leaks_within_solaris .)
Since C++20 you can use std::source_location which offers:
For previous versions of C++, traditionnally the macros __LINE__
gives the line number but also __FUNCTION__
and __FILE__
are really helpful, giving the const char* of the enclosing function, and file name.
Indeedn, __FUNCTION__
is not standard but supported by several compilers.
Unfortunately these macros only take their value in place. So it is not possible for you to ask for the caller.
You should write the __LINE__
and __FILE__
macros everywhere you use new
. :(.