From 1c9e1ddbcb3d1b9479fa9fd42a738063ee9cc125 Mon Sep 17 00:00:00 2001 From: dmiller Date: Fri, 29 Jul 2022 15:21:13 +0000 Subject: [PATCH] Improve assertions in gh_heap * Assert index matches any time a node is accessed by index, subsuming the assertion from #2139. * Ensure all removed nodes are invalidated, so double-removes will trigger assertion failure. Added a test for this. --- nsock/src/gh_heap.c | 19 ++++++++++--------- nsock/tests/ghheaps.c | 1 + 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/nsock/src/gh_heap.c b/nsock/src/gh_heap.c index 0eba8ecf4..3f759961c 100644 --- a/nsock/src/gh_heap.c +++ b/nsock/src/gh_heap.c @@ -70,7 +70,9 @@ static gh_hnode_t **hnode_ptr(gh_heap_t *heap, unsigned int index) { assert(index <= heap->count); - return &(heap->slots[index]); + gh_hnode_t **ptr = &(heap->slots[index]); + assert(index == heap->count || (*ptr)->index == index); + return ptr; } gh_hnode_t *gh_heap_find(gh_heap_t *heap, unsigned int index) { @@ -94,7 +96,6 @@ static int hnode_up(gh_heap_t *heap, gh_hnode_t *hnode) parent_idx = (cur_idx - 1) >> 1; parent_ptr = hnode_ptr(heap, parent_idx); - assert((*parent_ptr)->index == parent_idx); if (heap->cmp_op(*parent_ptr, hnode)) break; @@ -235,13 +236,13 @@ int gh_heap_remove(gh_heap_t *heap, gh_hnode_t *hnode) count--; last = *hnode_ptr(heap, count); heap->count = count; - if (last == hnode) - return 0; - - last->index = cur_idx; - *cur_ptr = last; - if (!hnode_up(heap, *cur_ptr)) - hnode_down(heap, *cur_ptr); + if (last != hnode) + { + last->index = cur_idx; + *cur_ptr = last; + if (!hnode_up(heap, *cur_ptr)) + hnode_down(heap, *cur_ptr); + } gh_hnode_invalidate(hnode); return 0; diff --git a/nsock/tests/ghheaps.c b/nsock/tests/ghheaps.c index 11f3327a9..d2e0cbdfc 100644 --- a/nsock/tests/ghheaps.c +++ b/nsock/tests/ghheaps.c @@ -63,6 +63,7 @@ static int ghheap_ordering(void *tdata) { gh_hnode_t *current; current = gh_heap_pop(&heap); + assert(!gh_hnode_is_valid(current)); k = node2int(current); if (k < n)