Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

are strtol, strtoll, strtod safe for any chars, even not null terminated?

Tags:

c

string

linux

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?

like image 928
Mickey Shine Avatar asked Mar 10 '12 00:03

Mickey Shine


1 Answers

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, and strtold functions:

The strtod, strtof, and strtold functions convert the initial portion of the string pointed to by nptr to double, float, and long 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.

like image 134
Keith Thompson Avatar answered Sep 28 '22 12:09

Keith Thompson