What's wrong with this `GLib.DateTime.unref` method call?

From the documentation of GLib.DateTime, I read that when I get a new DateTime object, I should release it with its method unref when I’m done with it.

So why when running the following test.js program, almost every time ten seconds after its launch I get the error g_date_time_unref: assertion 'datetime->ref_count > 0' failed ? Removing the unref call prevents the issue.

// test.js

const GLib = imports.gi.GLib;
const Mainloop = imports.mainloop;

class Hour_of_now {
    constructor() {
        const now = GLib.DateTime.new_now_local();
        this.hour = now.get_hour();
        
        now.unref(); // I'm done with it, so release it.
    }

    get() { return this.hour; }
}

const hour = new Hour_of_now();
log(hour.get());

Mainloop.run();
$ gjs --version
gjs 1.80.2
$ gjs test.js
Gjs-Message: 16:34:13.528: JS LOG: 16

(gjs:371836): GLib-CRITICAL **: 16:34:23.971: g_date_time_unref: assertion 'datetime->ref_count > 0' failed

Memory management is automatic in JavaScript, you don’t need to manually unref most objects (although there are some exceptions — see the guide).

1 Like

Thanks.

  1. So why the gjs reference documentation I linked advises to do it ?

  2. The tips guide you linked is not very explicit about it. The only maybe reference to this I can read is

Put simply, as long as GJS can trace a GObject to a variable, it will ensure the reference count does not drop to 0.

which doesn’t mean that a variables referencing the object having left its scope decrements the reference counter.

  1. Finally, why having called unref would be a critical error ? Why calling unref too much would be a problem for memory management ?

Because the JS API reference is generated from the C API reference, where reference counting is manual.

Because once the last reference to something is released, the underlying C memory is freed, and any subsequent access is a use-after-free, which could crash your application, self-destruct your computer, or cause vacuum decay in the local bubble of space time.

The general rule is: do not overthink it, and don’t do manual memory management. In other words:

Most developers will never have to worry about GObject referencing or memory leaks, especially if writing clean, uncomplicated code.

2 Likes

Be the chaos you want to see in the universe :supervillain:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.