Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Record dynamic memory allocation usage

Recently I am involved in a C project on a micro controller. There are many malloc() or calloc() in our project. My question is about is it possible to use an array or another dynamic allocate array in runtime to record the allocated memory existing duration, i.e the time from the memory has been allocated till it has been freed , and where it was freed. Thanks for any help.

like image 293
Yen Hung Liu Avatar asked Sep 18 '26 21:09

Yen Hung Liu


2 Answers

To do this "by hand", first, you need to replace all instances of malloc, calloc and free with your own functions (eg _malloc, _calloc and _free). For production, these can be defined as the original functions thereby carrying no overhead but for debug code, you have them call your own functions:

#ifdef _DEBUG
#define _malloc(s) myMalloc(s,__FILE__, __LINE__)
#define _calloc(b,n) myCalloc (b,n,__FILE__, __LINE__)
#define _free(p) myFree (p, __FILE__, __LINE__)
#else
#define _malloc malloc   //  If not debugging, just use the default
#define _calloc calloc
#define _free   free
#endif

#ifdef _DEBUG // Or whatever your compiler preset is
void *myMalloc (size_t sz, const char *pszFile, unsigned long line)
{
    //  Save the details in a table with the time
    ...
    return malloc (sz);
}
void myFree (void *ptr, const char *pszFile, unsigned long line)
{
    //  Process the table, do time calculations etc and then remove it
    free (ptr);
}
#endif

This is the only way to really overload malloc and free. The constants FILE and LINE will tell you where the memory was allocated and freed. NB. If you are going to allocate table space in myMalloc, use malloc, not _malloc or you may get an infinite loop.

like image 182
Mike Avatar answered Sep 20 '26 14:09

Mike


If you are using glibc, you can use its mtrace function and tool to trace all memory allocations and releases, without changes to your source code.

The mtrace() function installs hook functions for the memory-allocation functions (malloc(3), realloc(3) memalign(3), free(3)). These hook functions record tracing information about memory allocation and deallocation. The tracing information can be used to discover memory leaks and attempts to free nonallocated memory in a program.

When mtrace() is called, it checks the value of the environment variable MALLOC_TRACE, which should contain the pathname of a file in which the tracing information is to be recorded. If the pathname is successfully opened, it is truncated to zero length.

It supplies a command line tool to interpret the trace file, also named mtrace.

reference:

http://linux.die.net/man/3/mtrace

http://linux.die.net/man/1/mtrace

like image 44
fluter Avatar answered Sep 20 '26 12:09

fluter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!