C runtime should clean up any resources, including open files, buffers, and allocated data. However, I like to use int atexit( void(*)(void)) , which will call registered functions on normal output. Also exit immediately if atexit returns a nonzero value, i.e. your function has not been registered.
#include <stdlib.h> void register_cleanup ( void ( *cleaner )( void )) { if ( atexit ( cleaner )) { fprintf ( stderr, "Error, unable to register cleanup: %s\n", strerror ( errno )) ; exit ( EXIT_FAILURE ) ; } }
Then exit malloc failure.
#include <stdlib.h> void *malloc_or_die ( size_t size ) { void *dataOut = malloc ( size ) ; if ( !dataOut ) { fprintf ( stderr, "Error, malloc: %s\n", strerror ( errno )) ; exit ( EXIT_FAILURE ) ; } return dataOut ; } void main() { register_cleanup ( cleaner_fnc ) ; ... void *data = malloc_or_die ( 42 ) ; do_stuff ( data ) ; return 0 ; }
Funmungus
source share