Skip to content

Commit 680f65a

Browse files
committed
fix(strings): safely handle integer overflow in str2num to prevent UB
1 parent e33b3eb commit 680f65a

1 file changed

Lines changed: 11 additions & 7 deletions

File tree

src/strings/stdlib_str2num.fypp

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -147,22 +147,26 @@ module stdlib_str2num
147147
return
148148
end if
149149
!----------------------------------------------
150-
v = 0
150+
v = 0
151151
do while( p<=len(s) )
152152
val = iachar(s(p:p))-digit_0
153153
if( val >= 0 .and. val <= 9 ) then
154+
155+
156+
if (v > (huge(v) - int(val, kind(v))) / 10) then
157+
stat = -1 !! Indicates integer overflow
158+
return
159+
end if
160+
154161
v = v*10 + val
155162
p = p + 1
156163
else
157164
exit
158165
end if
159166
end do
160-
if(v >= 0) then
161-
v = sign * v
162-
stat = 0
163-
else
164-
stat = -1 !! Indicates integer overflow
165-
end if
167+
168+
v = sign * v
169+
stat = 0
166170
end subroutine
167171
#:endfor
168172

0 commit comments

Comments
 (0)