Pregunta

Alright, the answer for this may be obvious, but if I understand it correctly I don't get their reasoning. From the glib documentation on GHashTable:

g_hash_table_new_full ()

Creates a new GHashTable like g_hash_table_new() with a reference count of 1
and allows to specify functions to free the memory allocated for the key and
value that get called when removing the entry from the GHashTable.

Alright, fair enough. But what's the deal with g_hash_table_new? Does it automatically free simple data (strings, etc) and if not, what's the use case for such a dangerous and leaky function? Is it for limited-use situations where data is written but never deleted?

¿Fue útil?

Solución

A leak occurs when you call malloc and lose track of the return value before you get a chance to call free. That has nothing to do with hash tables a priori.

It's perfectly reasonable to have a hash table that maps string literals to integers, for example, in which case a user would never call malloc at all. Then there's no need to specificy deleter functions explicitly that do nothing.

Otros consejos

According to https://git.gnome.org/browse/glib/tree/glib/ghash.c?id=eff8f7511e08c73425fa65c9eaceb7dacf456f7a#n106 , g_hash_table_new() is the same as g_hash_table_new_full with NULL deallocation methods, so no freeing is performed.

The function is dangerous/leaky iff you use it on data that needs to be deallocated. It is non-leaky when you have keys/values that are values (ints cast to pointers) or memory that is managed elsewhere (e.g., pointers into an mmapped file, or into an array of data structures that you are managing differently).

By C standards this is pretty harmless.

it's not really a leak, unless you forget to free the data (which is pretty much a tautology :-)).

you're probably thinking that all hash tables should use allocated strings and g_str_hash as the hashing function.

GHashTable can use various types of keys. not ever key needs to be freed — for instance, if you pass NULL to the hash function (or g_direct_hash, which is exactly the same thing) then you use memory addresses as keys, so you don't have anything to free — i.e. you're not leaking memory.

there's also the case of having the key stored inside the value data, in case you have complex data structures stored inside the GHashTable, e.g.:

typedef struct { char *foo; int bar; double baz; } Value;

GHashTable *table;
Value *value;

table = g_hash_table_new_full (g_str_hash, g_str_equal, NULL, free_value);

// fill up the Value data structure
value = value_init (value_alloc (), "foo", 42, M_PI / 4.0);

g_hash_table_insert (table, value->foo, value);

it would be pointless (and possibly a performance or memory usage issue) to copy the key out of the data structure for every insertion and removal.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top