glibgnomevalagenie

vala genie freeing memory


My understanding is that Vala and Genie have reference counting rather than garbage collection.

Per Valadoc.org, this:

string path = Path.build_filename ("my", "full", "path/to.txt");

yields this:

a newly-allocated string that must be freed with g_free

Is this correct or is g_free not required due to reference counting?

If string is wrapped within an object will g_free on string be actioned on object destruction?


Solution

  • Valadoc contains the documentation from the original GLib, GObject, Gtk+, etc. libraries. It also contains additional Vala specific documentation on top of that.

    You often see sentences which only makes sense in the context of the C programming language.

    The Vala compiler does the memory management for you (most of the time). In this example a Vala string is actually translated by the Vala compiler to a gchar * in C where it has to be deallocated using g_free which the Vala compiler also does for you.

    As a matter of fact strings are a bit different than objects as they are not reference counted, but copied instead.

    Take this example in Vala:

    int main () {
      Object obj1 = new Object ();
      Object obj2 = obj1;
    
      string s1 = "";
      string s2 = s1;
      return 0;
    }
    

    The (manually cleaned up) code that valac produces in C looks like this:

    int main (void) {
        GObject* obj1 = g_object_new (G_TYPE_OBJECT, NULL);
        GObject* obj2 = g_object_ref (obj1);
        gchar* s1 = g_strdup ("");
        gchar* s2 = g_strdup (s1);
        g_free (s2);
        g_free (s1);
        g_object_unref (obj2);
        g_object_unref (obj1);
        return 0;
    }
    

    As you can see obj2 is a reference to the same object as in obj1 and the object is only destroyed when both references are unrefed.

    The string s2 on the other side is a copy of the string stored in s1 (which is in turn a copy of the string literal "").

    As you can also see the compiler does take care of such details for you. It makes the manual reference counting and manual string copying automatic.