Adds checks for memory allocation failures. Started to use calloc() instead of malloc()/memset(), but I got carried away. This kind of work should be done throughout the tree, but it's almost hopeless at present.