diff options
author | Jonathan Nieder <jrnieder@gmail.com> | 2010-12-05 03:35:17 -0600 |
---|---|---|
committer | Junio C Hamano <gitster@pobox.com> | 2010-12-07 16:03:55 -0800 |
commit | 97a5e3453abf63bbf5926979fcd89efb4388e937 (patch) | |
tree | 1b07e107f8a422abfb1ba749c6e1502274b8cbb5 /test-treap.c | |
parent | b0ad24be8ca9acd86393ce099d3217872d838915 (diff) | |
download | git-97a5e3453abf63bbf5926979fcd89efb4388e937.tar.gz |
treap: make treap_insert return inserted node
Suppose I try the following:
struct int_node *node = node_pointer(node_alloc(1));
node->n = 5;
treap_insert(&root, node);
printf("%d\n", node->n);
Usually the result will be 5. But since treap_insert draws memory
from the node pool, if the caller is unlucky then (1) the node pool
will be full and (2) realloc will be forced to move the node pool to
find room, so the node address becomes invalid and the result of
dereferencing it is undefined.
So we ought to use offsets in preference to pointers for references
that would remain valid after a call to treap_insert. Tweak the
signature to hint at a certain special case: since the inserted node
can change address (though not offset), as a convenience teach
treap_insert to return its new address.
So the motivational example could be fixed by adding "node =".
struct int_node *node = node_pointer(node_alloc(1));
node->n = 5;
node = treap_insert(&root, node);
printf("%d\n", node->n);
Based on a true story.
Signed-off-by: Jonathan Nieder <jrnieder@gmail.com>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
Diffstat (limited to 'test-treap.c')
-rw-r--r-- | test-treap.c | 11 |
1 files changed, 8 insertions, 3 deletions
diff --git a/test-treap.c b/test-treap.c index cdba5111e1..ab8c951c6e 100644 --- a/test-treap.c +++ b/test-treap.c @@ -38,9 +38,14 @@ int main(int argc, char *argv[]) usage("test-treap < ints"); while (strbuf_getline(&sb, stdin, '\n') != EOF) { - item = node_alloc(1); - strtonode(node_pointer(item), sb.buf); - treap_insert(&root, node_pointer(item)); + struct int_node *node = node_pointer(node_alloc(1)); + + item = node_offset(node); + strtonode(node, sb.buf); + node = treap_insert(&root, node_pointer(item)); + if (node_offset(node) != item) + die("inserted %"PRIu32" in place of %"PRIu32"", + node_offset(node), item); } item = node_offset(treap_first(&root)); |