diff --git a/src/ccutil/elst.cpp b/src/ccutil/elst.cpp index 70798831e..31da7815a 100644 --- a/src/ccutil/elst.cpp +++ b/src/ccutil/elst.cpp @@ -103,33 +103,29 @@ int32_t ELIST::length() const { // count elements void ELIST::sort( // sort elements int comparator( // comparison routine const void *, const void *)) { - ELIST_ITERATOR it(this); - int32_t count; - ELIST_LINK **base; // ptr array to sort - ELIST_LINK **current; - int32_t i; + // Allocate an array of pointers, one per list element. + auto count = length(); - /* Allocate an array of pointers, one per list element */ - count = length(); - base = static_cast(malloc(count * sizeof(ELIST_LINK *))); + if (count > 0) { + // ptr array to sort + std::vector base; + base.reserve(count); - /* Extract all elements, putting the pointers in the array */ - current = base; - for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) { - *current = it.extract(); - current++; + ELIST_ITERATOR it(this); + + // Extract all elements, putting the pointers in the array. + for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) { + base.push_back(it.extract()); + } + + // Sort the pointer array. + qsort(&base[0], count, sizeof(base[0]), comparator); + + // Rebuild the list from the sorted pointers. + for (auto current : base) { + it.add_to_end(current); + } } - - /* Sort the pointer array */ - qsort(base, count, sizeof(*base), comparator); - - /* Rebuild the list from the sorted pointers */ - current = base; - for (i = 0; i < count; i++) { - it.add_to_end(*current); - current++; - } - free(base); } // Assuming list has been sorted already, insert new_link to