2

I have a complex code base in C++. I have run a memory profiler that counts the number of bytes allocated by malloc, this gives me X bytes. Theoretically, my code should return X-Y bytes (Y varies with the input, and ranges from a few KB to a couple of GB, so this is not negligible.)

I need to find out which part of my code is asking for the extra bytes. I've tried a few tools, but to no avail: massif, perf, I've even tried gdb breaking on malloc(). I could probably write a wrapper for malloc asking to provide the calling function, but I don't know how to do that.

Does anyone know a way to find how much memory different parts of the program are asking for?

Dervin Thunk
  • 19,515
  • 28
  • 127
  • 217

2 Answers2

2

If you use a custom allocate function - a wrapper around malloc - you can use the gcc backtrace functions (http://man7.org/linux/man-pages/man3/backtrace.3.html) to find out which functions call malloc with what arguments.

That'll tell you the functions which are allocating. From there you can probably sort the biggies into domains by hand.

This question has good info on the wrapping itself. Create a wrapper function for malloc and free in C

Update: This won't catch new/delete allocations but overriding them is even easier than malloc! See here: How to properly replace global new & delete operators + the very important comment on the best answer "Don't forget the other 3 versions: new[], delete[], nothrow"

Community
  • 1
  • 1
Daniel
  • 1,994
  • 15
  • 36
0

You can make a macro that calls the libc malloc and prints the details of the allocation.

#define malloc( sz ) (\
{\
    printf( "Allocating %d Bytes, File %s:%d\n", sz, __FILE__, __LINE__ );\
    void *(*libc_malloc)(size_t) = dlsym(RTLD_NEXT, "malloc");\
    printf("malloc\n");\
    void* mem = libc_malloc(sz);\
    mem; // GCC-specific statement-expression \
}

This should ( touch wood ) get called in lieu of the real malloc and spit out the number of bytes allocated and where the allocation occurred. Returning mem like this is GCC-specific though.

wrren
  • 1,281
  • 9
  • 11