Build a Robust Long-to-ASCII Conversion Function

Audience: Beginning C programming students

Objectives

  1. Students will perform input validation checking
  2. Students will learn how to handle errors and exceptions

Exercise

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:

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:

  1. no error has occurred; or
  2. numstr points to something that is not a valid decimal integer (this includes numstr being NULL); or
  3. 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
  4. overflow occurred, and the number being read was negative. The result of the function is undefined.

Discussion questions

  1. Are there errors other than the three above types that could occur?
  2. What happens if errcode is not a valid pointer?