[RFA] Fix leak detected in GDB test gdb.base/macscp.exp
Commit Message
When a node is removed from a splay tree, the splay tree was
not using the function splay_tree_delete_key_fn to release the key.
Fix the leak by calling the delete key function when removing a node.
Also, clarify the documentation about when the release functions are
called.
include/ChangeLog
2019-01-19 Philippe Waroquiers <philippe.waroquiers@skynet.be>
* splay-tree.h (splay_tree_delete_key_fn): Update comment.
libiberty/ChangeLog
2019-01-19 Philippe Waroquiers <philippe.waroquiers@skynet.be>
* splay-tree.c (splay_tree_remove): Call sp->delete_key.
(splay_tree_new_typed_alloc): Update comment.
---
include/splay-tree.h | 5 ++++-
libiberty/splay-tree.c | 18 +++++++++++++++++-
2 files changed, 21 insertions(+), 2 deletions(-)
@@ -58,7 +58,10 @@ typedef struct splay_tree_node_s *splay_tree_node;
typedef int (*splay_tree_compare_fn) (splay_tree_key, splay_tree_key);
/* The type of a function used to deallocate any resources associated
- with the key. */
+ with the key. This is called to release the keys present in the
+ tree when calling splay_tree_delete or splay_tree_remove. The
+ caller of splay_tree_insert might have to call it if the same key
+ value is re-inserted in the tree. */
typedef void (*splay_tree_delete_key_fn) (splay_tree_key);
/* The type of a function used to deallocate any resources associated
@@ -318,7 +318,21 @@ different types need to be allocated with different allocators.
The splay tree will use @var{compare_fn} to compare nodes,
@var{delete_key_fn} to deallocate keys, and @var{delete_value_fn} to
-deallocate values.
+deallocate values. Keys and values will be deallocated when the
+tree is deleted using splay_tree_delete or when a node is removed
+using splay_tree_remove. splay_tree_insert will release the previous
+value using @var{delete_value_fn} if the inserted key is already found
+in the tree. In such a case, if the caller has allocated a new key
+to call splay_tree_insert, it is the responsibility of the caller to
+release the newly allocated key, as the tree does not take ownership
+of the key given in argument in case of re-insertion of the same key
+value. So, typically, the caller might do:
+ splay_tree_key k = ...allocate a key ...;
+ splay_tree_node s = splay_tree_insert (tree, k, value);
+ if ((struct macro_key *) s->key != k)
+ macro_tree_delete_key (k);
+to ensure the newly allocated splay_tree_key k is released when the same
+k value was already present in the tree.
@end deftypefn
@@ -427,6 +441,8 @@ splay_tree_remove (splay_tree sp, splay_tree_key key)
/* Delete the root node itself. */
if (sp->delete_value)
(*sp->delete_value) (sp->root->value);
+ if (sp->delete_key)
+ sp->delete_key (sp->root->key);
(*sp->deallocate) (sp->root, sp->allocate_data);
/* One of the children is now the root. Doesn't matter much