Proper Usage of strtol with Error Handling
The following C or C program converts strings to long integers, relying on the fact that strtol returns NULL for successful conversions. However, when given the value 55, it fails with the following message:
./convertToLong 55 Could not convert 55 to long and leftover string is: 55 as long is 55
This article explores how to correctly detect errors in strtol and address the issue in the given program.
Error Handling in strtol
The official specification for strtol (and related functions like strtoll) states that:
Correcting the Program
In C, errors from strtol can be detected by setting errno to zero before calling the function. The modified parseLong function below follows this approach:
static long parseLong(const char *str) { errno = 0; char *temp; long val = strtol(str, &temp, 0); if (temp == str || *temp != '<pre class="brush:php;toolbar:false">bool parseLong(const char *str, long *val) { char *temp; bool rc = true; errno = 0; *val = strtol(str, &temp, 0); if (temp == str || *temp != '' || ((*val == LONG_MIN || *val == LONG_MAX) && errno == ERANGE)) rc = false; return rc; }
In C , a more flexible approach is to return a success/failure indicator and provide a separate function for extracting the converted value:
Conclusion
With these modifications, the parseLong function correctly handles errors from strtol, allowing applications to determine the success or failure of conversions and handle errors appropriately.
The above is the detailed content of How Can I Properly Handle Errors When Using strtol in C and C ?. For more information, please follow other related articles on the PHP Chinese website!