1

I'm using GNU Linear Programming Kit at my program. Everything works fine, but when I checked program with valgrind I found some memory leaks:

==7051== 160 bytes in 1 blocks are still reachable in loss record 1 of 3
==7051==    at 0x4C28BED: malloc (vg_replace_malloc.c:263)
==7051==    by 0x52CFACB: glp_init_env (in /usr/lib/libglpk.so.0.30.0)
==7051==    by 0x52CFC1C: ??? (in /usr/lib/libglpk.so.0.30.0)
==7051==    by 0x52D0211: glp_malloc (in /usr/lib/libglpk.so.0.30.0)
==7051==    by 0x52AC50A: glp_create_prob (in /usr/lib/libglpk.so.0.30.0)

According to documentation glp_init_env(void) is called on first use of any GLPK API call. But to clean it up, one would have need to call glp_free_env(void).

I want my program to be memory leak free, and simply calling glp_free_env(); manually isn't a good solution for me - I have some unit tests written with Boost Unit Test Framework and I want them to be memory leak free too.

Ideally I would use some C++ feature that could call it automatically on program termination. Do you know any simple and clean way do do it?

4

2 回答 2

1

如果benjymous的答案由于某种原因不合适,std::atexit可能会有所帮助:

int atexit( void (*func)() );

注册 func 指向的函数,以便在正常程序终止时调用(通过 std::exit() 或从 cpp/language/main 函数返回)

于 2014-02-14T17:20:39.053 回答
1

像这样的东西应该工作

class CleanupOnExit
{
public:
    ~CleanupOnExit()
    {
        glp_free_env(void);
    }
};

int main ()
{
    CleanupOnExit cleanup;

    .. do any processing here ..

    return 0;
}

cleanup的析构函数会在结束时自动调用main(即使你在中间返回,或者抛出异常。)

于 2014-02-14T17:11:59.770 回答