@@ 18,6 18,7 @@
int main(int argc, char **argv)
{
struct sc_hashtable hash;
+ struct sc_iterator iter;
char *line = NULL, *key, *value, *oldvalue, *index;
size_t len = 0;
size_t keylen, vallen;
@@ 39,20 40,27 @@ int main(int argc, char **argv)
if (index) {
/* Set key=val */
*index = '\0';
+ key = line;
- keylen = strlen(line);
- key = malloc(keylen + 1);
- strncpy(key, line, keylen + 1);
-
+ /* Since we're creating a new value, we'll need to
+ * allocate a new buffer regardless. Do that now. */
index++;
vallen = strlen(index);
value = malloc(vallen + 1);
strncpy(value, index, vallen + 1);
+ /* Check whether the key already exists in the hash */
oldvalue = sc_ht_get_ptr(&hash, key);
if (oldvalue) {
+ /* If so, free the old value associated. */
printf("deleting %s=%s\n", key, oldvalue);
free(oldvalue);
+ } else {
+ /* If not, we'll need to allocate a new key
+ * object which will be stored into the hash. */
+ keylen = strlen(line);
+ key = malloc(keylen + 1);
+ strncpy(key, line, keylen + 1);
}
sc_ht_insert_ptr(&hash, key, value);
} else {
@@ 66,7 74,20 @@ int main(int argc, char **argv)
printf("> ");
}
- /* TODO: iteration over keys & values to free */
+ /* Free each key and value from the hash table. */
+ iter = sc_ht_iter_keys_ptr(&hash);
+ while (iter.has_next(&iter)) {
+ key = iter.next(&iter);
+ value = sc_ht_get_ptr(&hash, key);
+ /* NOTE: here we do not use sc_ht_remove_ptr(). This is because
+ * modifying a hash while iterating is not yet supported.
+ * There's no harm in leaving values in the hash table as we
+ * free them; the hash table will never try to dereference
+ * pointers. */
+ free(key);
+ free(value);
+ }
+ iter.close(&iter);
free(line);
sc_ht_destroy(&hash);
@@ 7,6 7,7 @@ sources = [
libsc_collections_dep = dependency(
'sc-collections',
fallback : ['sc-collections', 'libsc_collections_dep'],
+ version : '>=0.2.0',
)
executable(