diff options
author | Pádraig Brady <P@draigBrady.com> | 2010-07-13 08:23:52 +0100 |
---|---|---|
committer | Pádraig Brady <P@draigBrady.com> | 2010-07-13 16:51:38 +0100 |
commit | f8574063d566bbf08dbf2dc469f055f13684e525 (patch) | |
tree | 52419002a73e902df5b96ff2a25bf5f8d2725cf8 /gl | |
parent | 9face836f36c507f01a7d7a33138c5a303e3b1df (diff) | |
download | coreutils-f8574063d566bbf08dbf2dc469f055f13684e525.tar.xz |
maint: heap.c: simplify dynamic allocations
* gl/lib/heap.c (heap_alloc): Use the fact that the xalloc
routines will not return NULL. Also remove the redundant
temporary variables.
(heap_insert): From Jim Meyering, use x2nrealloc() which
is simpler while handling overflow and increasing the
size more efficiently. This reallocation is currently
unused by coreutils in any case as it preallocates enough.
Diffstat (limited to 'gl')
-rw-r--r-- | gl/lib/heap.c | 27 |
1 files changed, 5 insertions, 22 deletions
diff --git a/gl/lib/heap.c b/gl/lib/heap.c index a37224fa0..1de3391a5 100644 --- a/gl/lib/heap.c +++ b/gl/lib/heap.c @@ -36,22 +36,12 @@ static void heapify_up (void **, size_t, struct heap * heap_alloc (int (*compare)(const void *, const void *), size_t n_reserve) { - struct heap *heap; - void *xmalloc_ret = xmalloc (sizeof *heap); - heap = (struct heap *) xmalloc_ret; - if (!heap) - return NULL; + struct heap *heap = xmalloc (sizeof *heap); - if (n_reserve <= 0) + if (n_reserve == 0) n_reserve = 1; - xmalloc_ret = xmalloc (n_reserve * sizeof *(heap->array)); - heap->array = (void **) xmalloc_ret; - if (!heap->array) - { - free (heap); - return NULL; - } + heap->array = xmalloc (n_reserve * sizeof *(heap->array)); heap->array[0] = NULL; heap->capacity = n_reserve; @@ -82,15 +72,8 @@ int heap_insert (struct heap *heap, void *item) { if (heap->capacity - 1 <= heap->count) - { - size_t new_size = (2 + heap->count) * sizeof *(heap->array); - void *realloc_ret = xrealloc (heap->array, new_size); - heap->array = (void **) realloc_ret; - heap->capacity = (2 + heap->count); - - if (!heap->array) - return -1; - } + heap->array = x2nrealloc (heap->array, &heap->capacity, + sizeof *(heap->array)); heap->array[++heap->count] = item; heapify_up (heap->array, heap->count, heap->compare); |