malloc_count
malloc_count copied to clipboard
memprofile.h Segmentation fault
Hi I like the library, but I tried to use the example with memprofile.h and this gave segmentation fault when I call to
MemProfile mp("memprofile.txt", 0.1, 1024);
is there a way to solve this? My g++ version is
gcc version 9.4.0 (Ubuntu 9.4.0-1ubuntu1~20.04.1)
Hey, I also encountered this problem.
The reason for the segment fault is that fprintf will call malloc in the underlying implementation, and this will trigger callback in the end.
So this code would goes like:
malloc() -> inc_count() -> callback() -> fprintf() -> malloc() -> ...
And this endless loop will go on until the stack overflows.
My solution is to add a guard var
running_callbackto prevent recursive calling:
// malloc_count.c
static bool running_callback = false;
void set_running_callback(bool running)
{
running_callback = running;
}
static void inc_count(size_t inc)
{
if (callback && !running_callback) callback(curr);
}
static void dec_count(size_t dec)
{
if (callback && !running_callback) callback(curr);
}
// malloc_count.h
extern void set_running_callback(bool running);
// memprofile.h
inline void callback(size_t memcurr)
{
set_running_callback(true);
...
set_running_callback(false);
}