Domanda

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?

È stato utile?

Soluzione

If benjymous's answer isn't appropriate for some reason or other, std::atexit may help:

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

Registers the function pointed to by func to be called on normal program termination (via std::exit() or returning from the cpp/language/main function)

Altri suggerimenti

Something like this should work

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

int main ()
{
    CleanupOnExit cleanup;

    .. do any processing here ..

    return 0;
}

cleanup's destructor will be called automatically at the end of main (even if you return in the middle, or throw an exception.)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top