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 <anatol.pomo...@gmail.com> 
>> 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.


> 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