Make it safe to delete keys while iterating with the json_object_object_foreach macro.

This commit is contained in:
Eric Haszlakiewicz
2012-10-20 20:26:37 -05:00
parent 5abc0ea444
commit f6b27cbb6c
3 changed files with 36 additions and 6 deletions

View File

@@ -16,9 +16,29 @@ int main(int argc, char **argv)
json_object *my_object = json_object_new_object();
json_object_object_add(my_object, "foo1", json_object_new_string("bar1"));
json_object_object_add(my_object, "foo2", json_object_new_string("bar2"));
json_object_object_add(my_object, "deleteme", json_object_new_string("bar2"));
json_object_object_add(my_object, "foo3", json_object_new_string("bar3"));
const char *original_key = NULL;
printf("==== delete-in-loop test starting ====\n");
int orig_count = 0;
json_object_object_foreach(my_object, key0, val0)
{
printf("Key at index %d is [%s]", orig_count, key0);
if (strcmp(key0, "deleteme") == 0)
{
json_object_object_del(my_object, key0);
printf(" (deleted)\n");
}
else
printf(" (kept)\n");
orig_count++;
}
printf("==== replace-value first loop starting ====\n");
const char *original_key = NULL;
orig_count = 0;
json_object_object_foreach(my_object, key, val)
{
printf("Key at index %d is [%s]\n", orig_count, key);

View File

@@ -1,3 +1,9 @@
==== delete-in-loop test starting ====
Key at index 0 is [foo1] (kept)
Key at index 1 is [foo2] (kept)
Key at index 2 is [deleteme] (deleted)
Key at index 3 is [foo3] (kept)
==== replace-value first loop starting ====
Key at index 0 is [foo1]
Key at index 1 is [foo2]
replacing value for key [foo2]