Memory Profiler for C

I need a memory profiler to know the memory usage for each function. I know valgrind (Massif), but it does not give me information about specific functions (at least I don't know how to do this with an array)

Do you know any tool for this purpose in Linux?

Thanks!

+8
c memory profiler valgrind
source share
4 answers

You can take a look at MemProf .

+4
source share

If you just want to get the place where a large amount of memory is being requested from, the easiest way would be to install the malloc function or create a new library with a call to malloc and track the size of the malloc function form. I'm not talking about implementing a malloc call. LD_PRELOAD this library for your application.

Here is a sample code:

 /* * gcc -shared -fPIC foo.c -ldl -Wl,-init,init_lib -o libfoo.so * * LD_PRELOAD this library in the environment of the target executable * */ #include <stdio.h> #include <sys/time.h> #include <dlfcn.h> #include <stdlib.h> #include <sys/errno.h> #ifndef RTLD_NEXT #define RTLD_NEXT ((void *)-1) #endif int init_lib(void) { return 0; } void *malloc(size_t size) { /* do required checks on size here */ return ((void* (*)(size_t))(dlsym(RTLD_NEXT, "malloc")))(size); } 

You can very well modify this code to do some extra things.

+4
source share

Massif shows which functions were responsible for memory usage if you compiled your program with debugging information ( -g ). It will even show you the line number.

This information is provided as a call tree in each detailed snapshot below the graph in the ms_print output. The frequency of detailed snapshots can be controlled using the --detailed-freq parameter for the array. See section 9.2.6 of the Massif manual for details on reading the detailed snapshot information.

+3
source share

As others have pointed out, Massif provides comprehensive information for profiling, but it significantly slows down the process.

Another option is Google tcmalloc, which has a built-in heap profiler that resets the call graph with selections (see http://goog-perftools.sourceforge.net/doc/heap_profiler.html ), which can also be graphically rendered.

You can link it at run time to your program using LD_PRELOAD , and the HEAPPROFILE env variable includes a heap profiler.

+2
source share

Source: https://habr.com/ru/post/650663/


All Articles