views:

75

answers:

5

I have a class that uses libxml2. It has static members which are used to hold context for a schema file and its parser. I'm using valgrind, and it's complaining that memory is not deallocated in connection with the schema context. This is because you need to free that memory yourself. However, since these context variables are static, I can't free on destruction of the object. Is there a way to call the necessary free functions, or should I just ignore valgrind.

+2  A: 

Set up an atexit handler and free there. Or ignore.

bmargulies
A: 

If the valgrind error is showing up when the process ends, then I wouldn't worry about it. Why are the context variables static though?

You can generate a suppressions file that will make valgrind ignore the errors associated with your static contexts. See this page in the valgrind manual: suppressing errors

mch
Basically, the class is a "reader" and there is only one valid schema for the program. So, on-demand, I read the schema and make the parsing context, but then any other readers created don't have to hit that file again.
Dave
+4  A: 

Declare another class within your XML-using class. In its destructor, clean up your static members. Now give the outer class another static member of the inner class type. By virtue of having a non-trivial destructor, it will get cleaned up as the program exits, and thus your other values will get cleaned up, too.

class UseLibXml {
  static int xmlvar;

  struct StaticCleanup {
    ~StaticCleanup() {
      CleanUpLibXmlVar(UseLibXml::xmlvar);
    }
  };

  static StaticCleanup static_cleanup;
};

Define UseLibXml::static_cleanup the same place you define the other static variables, in one of your .cpp files.

Rob Kennedy
Does it matter that you have `StaticCleanup` defined as a `struct` instead of `class` there?
Dave
By making it a struct, I didn't have to explicitly make the destructor public. Public versus private is the *sole* difference between structs and classes.
Rob Kennedy
Implemented this and it works. Thanks!
Dave
A: 

I think you can ignore this warnings, since they are not memory leaks. They memory occupied by them will return to OS as soon as your application exit

dimba
That is, if the application exit. What happens when you unload the library and reload it ?
Matthieu M.
A: 

I assume these static variables are pointers?

Assuming you have:

class X
{
     private:
        static Plop*   staicXData;  // Initialised in the code.
};

I would change it to:

Class X
{
    private:
        static Plop&  getStatoc()
        {
            static Plop  data;     // Auto created on first use.
                                   // Destroyed on program exit.
            return data;
        }
};
Martin York