Am 04.03.20 um 23:40 schrieb brainpower:
> Am 04.03.20 um 23:32 schrieb brainpower:
>> Hi!
>>
>> Am 04.03.20 um 22:29 schrieb Anatol Pomozov:
>>> On Wed, Mar 4, 2020 at 12:39 PM Anatol Pomozov <[email protected]> 
>>> wrote:
>>>> +               } else if(strcmp(key, "ConcurrentDownloadStreams") == 0) {
>>>> +                       /* TODO: what is the best way to handle int 
>>>> conversion errors? */
>>>> +                       config->concurrent_download_streams = atoi(value);
>>>
>>> Here is a question I have. What is the best way to handle int
>>> conversion errors for this option?
>>>
>>
>> I'd recommend strtol() [1] over atoi() any time.
>> It makes it a lot easier to get error handling right, well, in most cases 
>> actually possible at all!
>>
>> I do not know of any way to differentiate between a valid "0" input and the 
>> error case with atoi().
>> There is no way to detect if the input was out of range, atoi() just gives 
>> some undefined value.
>> (The only valid use case for atoi() I might find acceptable would be if you 
>> can be *absolutely* sure the input is a valid int. e.g. validate before 
>> passing to atoi)
>>
>>
>> With strtol() do the following:
>>
>> 1. Call strol()
>> 2. Check if *end is NULL, if it is not, parsing was aborted at the position 
>> *end points to
> 
> Sorry.
> I messed up and misread the documentation here. The first part of the above 
> is incorrect.
> 
> You'll have to check str != end, where str is the first pointer passed to 
> strtol and end the second.

ah, sorry. Not my day today.
I forgot to mention the
    if (str == end) { /* error */ }
check is incomplete, it'll only check if parsing did not fail at the first char.
So it would not detect garbage at the end of the string. "abc500" would be 
detected, "500abc" would get you 500 and discard the "abc".

With the case I had in mind where I needed this last, that behavior was the 
result I wanted, that's probably not be the case here.

If you want to detect garbage at the end you'll have to check if end points to 
the end of the string,
so something like  if ((end - str) < strlen(str)) { /* error */ } .


> 
>> 3. Check errno for ERANGE, it gets set if the integer given does not fit 
>> into a long
>> 4. Now use the number. Check range again, if you want to downcast the long 
>> to int.
>>
>> [1]: https://en.cppreference.com/w/c/string/byte/strtol
>>
>>
>>
> 
> 


-- 
regards,
brainpower

Attachment: signature.asc
Description: OpenPGP digital signature

Reply via email to