malloc_count icon indicating copy to clipboard operation
malloc_count copied to clipboard

memprofile.h Segmentation fault

Open ssalinasfe opened this issue 3 years ago • 1 comments

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)

ssalinasfe avatar Aug 18 '22 21:08 ssalinasfe

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_callback to 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);
}

Kymdon13 avatar Apr 17 '25 15:04 Kymdon13