¿Son strtol, strtoll, strtod seguros para cualquier carácter, incluso no terminados en nulo?

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?

preguntado el 10 de marzo de 12 a las 00:03

2 Respuestas


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.

Refiriéndose al último borrador of the 2011 ISO C standard:

7.1.1 Definition of terms:

A cadena 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.

El strtod, strtofy strtold funciones:

El strtod, strtofy strtold functions convert the initial portion of the cadena señalado por nptr a double, floaty long double representation, respectively.

(énfasis añadido)

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.

contestado el 04 de mayo de 18 a las 01:05

As long as your input is terminated somehow which is definitely not a valid digit character, processing will stop and shouldn't go happily reading memory until it finds the first NUL.

So I think you're ok.

respondido 10 mar '12, 00:03

So, for example, a blank or punctuation character (or letter when the base does not include that letter) after the converted number will stop the scan. - jonathan leffler

@JonathanLeffler: Except leading spaces, decimal points, anything else that could be valid input, yes. - ben voigt

@Ben - I was in time to fix my comment with the 'after the converted number' part which was definitely missing in the first revision and was definitely needed. - jonathan leffler

@BenVoigt: It no debe, but I see no guarantee in the standard that it no se. - Keith Thompson

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.