Build a Robust Long-to-ASCII Conversion Function
Audience: Beginning C programming students
- Students will perform input validation checking
- Students will learn how to handle errors and exceptions
The function atol(3) takes a pointer to a character string as an argument and
returns the integer value corresponding to that string. Unfortunately, it has several problems:
- Overflow is not detected;
- If the string is not a valid integer, it converts as much of the string as it can and then stops; and
- Most implementations do not handle a leading “+” sign.
Your job is to implement a new function called natol (for “new atol”) which handles all these problems.
Your function must have the interface:
long natol(char *numstr, int *errcode)
where numstr is a pointer to the string whose integer value is to be returned, and
errcode is a pointer to an integer variable which, when natol exits,
has one of the following values:
- no error has occurred; or
- numstr points to something that is not a valid decimal integer (this includes numstr being NULL); or
- overflow occurred, and the number being read was positive. The result of the function is undefined
(that is, you can make it return anything you like, but it must return something); or
- overflow occurred, and the number being read was negative. The result of the function is undefined.
- Are there errors other than the three above types that could occur?
- What happens if errcode is not a valid pointer?