Check for failed allocations and fix some resource leaks.