Fixed a number of memory and pointer bugs.

This commit fixes a dozen or so null pointer dereferences, double
frees and memory corruptions most of them discovered via clang's
static analyzer.