Web lists-archives.com

Re: Null check in g_hash_table_lookup()




On 15/08/15 22:14, Jasper St. Pierre wrote:
> It will fix it in that it will warn and then return NULL (and only if
> you build glib with the flag that turns those return_val_if_fail's on,
> which it does by default), but it's considered improper behavior to
> call g_hash_table_lookup with a NULL key.

As far as I understand it, adding this return_val_if_fail would be an
API break. At the moment, NULL is accepted, but is only correct to store
or look up if the hash table's hash and equality functions also accept
it. Some GHashTable functions even document this, for instance

    g_hash_table_lookup_extended:
    ...
    You can actually pass NULL for lookup_key to test whether the NULL
    key exists, provided the hash and equal functions of hash_table are
    NULL-safe.

g_str_equal, g_str_hash do not accept NULL as an argument, but for
instance g_direct_equal, g_direct_hash do. If you write your own hash
and equality functions, it's up to you whether NULL is accepted or not.

Not accepting NULL would break the relatively common case of hash tables
that use GINT_TO_POINTER(some_integer) keys, where the runtime value of
some_integer happens to be 0 sometimes. [1]

g_hash_table_lookup[_extended] do not annotate key as (allow-none),
which seems like a bug to me.

    S

[1] Strictly speaking this assumes a CPU architecture where NULL is
all-bits-zero, which is not actually guaranteed by ISO C; but in
practice, nothing in the GLib stack is going to work on architectures
where this assumption does not hold, because there's a pervasive
assumption that a struct with all-bits-zero has all its pointer members
set to NULL.

-- 
Simon McVittie
Collabora Ltd. <http://www.collabora.com/>

_______________________________________________
gtk-devel-list mailing list
gtk-devel-list@xxxxxxxxx
https://mail.gnome.org/mailman/listinfo/gtk-devel-list