#include #include "mcs360.h" /* void err_mesg( const char *function, const char *mesg). Displays the string Error in (function): (message) where (function) and (mesg) denote the values of the values of the string parameters function and mesg, and then terminates the program. */ void err_mesg( const char *function, const char *mesg) { fprintf( stderr, "\nError in %s: %s\n", function, mesg); exit(1); } /* void *checked_malloc( size_t size). Invoked exactly like C library function malloc(). Calls malloc() to allocate the memory and then checks the return value of malloc() and terminates the program if it is null. */ void *checked_malloc( size_t size) { void *addr = malloc(size); if ( addr == NULL ) { char mesg[60]; sprintf( mesg, "Requested memory (%u bytes) could not be allocated.", size); err_mesg( "checked_malloc()", mesg); } return addr; } /* void *checked_malloc( size_t size). Invoked exactly like C library function realloc(). Calls realloc() to resize the memory allocation and then checks the return value of realloc() and terminates the program if it is null. To resize a dynamic array a with element type T to a new size of n (elements), use a = (T *)checked_realloc( n*sizeof(T)); Note this won't work completely if there are other pointers into the dynamic array. */ void *checked_realloc( void *old_addr, size_t new_size) { void *new_addr = realloc( old_addr, new_size); if ( new_addr == NULL ) { char mesg[60]; sprintf( mesg, "Requested memory (%u bytes) could not be allocated.", new_size); err_mesg( "checked_realloc()", mesg); } return new_addr; }