Stop using atoi()/atol()/strtol(), convert all to str_to_*() and str_to_*_strict() #966
Labels
C-str
Issues and PRs about C/C++ methods, headers and data types dealing with strings and memory blocks
refactor/fightwarn
PR or issue proposal to improve code maintainability without functional changes, or to fix warnings
In the C programming language,
atoi()
andatol()
don't check errors. If the input string is invalid, their behavior is undefined with no guaranteed return value (a particular implementation of libc may have defined return value, but it's not guaranteed by the C standard).strtol()
is better, but its error checking is complicated, one need to test three conditions,errno != 0
for overflows and invalid integers,nptr != endptr
for strings without digits, and*endptr != '\0'
for strings mixed with letters and numbers, it is easily misused. Also, it ignores the leading space in the string that can hide bugs. *BSD'sstrtonum()
is the best function for this job, but it's not portable.To solve this problem, the NUT project already has a builtin library
common/str.c
that provides easy-to-use and portable string conversion functions with robust error handling, such asstr_to_short()
,str_to_ushort()
,str_to_long()
(they are implemented by callingstrtol()
with correct error checking), "strict" versions that report errors if there are leading spaces also exist. Unfortunately, these good string functions is used by almost nobody. They are only used by 3 drivers, and it's not used in server code at all.All
atoi()
,atol()
,strtol()
in the existing code should be converted to usestr_to_*()
instead, if it's not practical to convert existing code, at least they should be disallowed in new code. Ideally, the "strict" version of the functions should be preferred.The
new-drivers.txt
document should inform the developers about the existence of these functions.The text was updated successfully, but these errors were encountered: