I am trying to convert some chars into numeric type, but some of them may not be null-terminated strings. So are strtol, strtoll, strtod safe for those strings that aren't null-terminated?
No.
If a character array is not terminated by a null character, then it's not a string. If any of the strto*()
functions are passed an argument that doesn't point to a string, the behavior is undefined.
Referring to the latest draft of the 2011 ISO C standard:
7.1.1 Definition of terms:
A string is a contiguous sequence of characters terminated by and including the first null character.
7.1.4 Use of library functions:
If an argument to a function has an invalid value (such as a value outside the domain of the function, or a pointer outside the address space of the program, or a null pointer, or a pointer to non-modifiable storage when the corresponding parameter is not const-qualified) or a type (after promotion) not expected by a function with variable number of arguments, the behavior is undefined.
7.22.1.3 The
strtod
,strtof
, andstrtold
functions:The
strtod
,strtof
, andstrtold
functions convert the initial portion of the string pointed to by nptr todouble
,float
, andlong double
representation, respectively.
(emphasis added)
So an argument that doesn't point to a string is outside the domain of the function.
You're likely to get away with it if the array contains something like { '1', '2', '3', 'x', 'y', 'z' }
, since it doesn't need to scan past the x
that terminates the desired value, but the behavior is explicitly undefined.
If you want to use these functions, you should, if necessary, copy your array into another buffer and explicitly null-terminate it yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With