It is quite common to ignore the error return codes of standard library functions. This is dangerous. In the case of the int_stack example, malloc could fail because it had run out of memory.
The handling of library and system errors depends on the nature of the error. In the case of running out of memory, usually the best we can do is print out an error message and exit the program.
#include <stdlib.h>
#include <stdio.h>
int_stack
make_int_stack(void)
{
int_stack stack = xalloc(struct int_stack);
if( stack == 0 ) {
fprintf(stderr, "%s %d: out of memory\n", __FILE__, __LINE__);
abort();
}
x_max_int_stack(stack) = 16;
x_len_int_stack(stack) = 0;
x_vals_int_stack(stack) = xnalloc(int, 16);
if( x_vals_int_stack(stack) == 0 ) {
fprintf(stderr, "%s %d: out of memory\n", __FILE__, __LINE__);
abort();
}
}
This code uses 3 C constructs to implement the error code:
abort() is a portable way of causing the program to crash.
__FILE__ is replaced (during compilation) with the name
of the file containing the code (as a string).
__LINE__ is replaced (during compilation) with the
current line number (as an integer constant).
Warning: __FILE__ and __LINE__ were both standardized by ANSI C; they may not be supported by (really) old compilers.