Skip to content

Commit 1c385ff

Browse files
committed
Addition of checks on the size of array and index in sort_index
1 parent db0dbc8 commit 1c385ff

File tree

3 files changed

+26
-2
lines changed

3 files changed

+26
-2
lines changed

example/sorting/CMakeLists.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
ADD_EXAMPLE(ord_sort)
22
ADD_EXAMPLE(sort)
3+
ADD_EXAMPLE(sort_index)
34
ADD_EXAMPLE(radix_sort)
4-
ADD_EXAMPLE(sort_bitset)
5+
ADD_EXAMPLE(sort_bitset)
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
program example_sort_index
2+
use stdlib_sorting, only: sort_index
3+
implicit none
4+
integer, allocatable :: array(:)
5+
integer, allocatable :: index(:)
6+
7+
array = [5, 4, 3, 1, 10, 4, 9]
8+
allocate(index, mold=array)
9+
10+
call sort_index(array, index)
11+
12+
print *, array !print [1, 3, 4, 4, 5, 9, 10]
13+
print *, index !print [4, 3, 2, 6, 1, 7, 5]
14+
15+
end program example_sort_index

src/stdlib_sorting_sort_index.fypp

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ contains
9393
! deal with Fortran arrays of intrinsic types and not the full generality
9494
! of Rust's arrays and lists for arbitrary types. It also adds the
9595
! estimation of the optimal `run size` as suggested in Tim Peters'
96-
! original listsort.txt, and the optional `work` and `iwork` arraya to be
96+
! original listsort.txt, and the optional `work` and `iwork` arrays to be
9797
! used as scratch memory.
9898

9999
${t1}$, intent(inout) :: array(0:)
@@ -106,8 +106,16 @@ contains
106106
${t2}$, allocatable :: buf(:)
107107
${ti}$, allocatable :: ibuf(:)
108108

109+
if ( size(array, kind=int_index) > huge(1_${ki}$) ) then
110+
error stop "Too many entries for the chosen kind."
111+
end if
112+
109113
array_size = size(array, kind=${ki}$)
110114

115+
if ( size(index, kind=${ki}$) < array_size ) then
116+
error stop "index array is too small."
117+
end if
118+
111119
do i = 0, array_size-1
112120
index(i) = i+1
113121
end do

0 commit comments

Comments
 (0)